{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# Any results you write to the current directory are saved as output.","metadata":{"_uuid":"e36d38a4f30fd9a1f92664f5af0a78b58f19df25","_cell_guid":"0e7c9cd9-2aa7-4a1b-9454-60c4b8b8f7c6","execution":{"iopub.status.busy":"2022-05-08T20:25:48.372619Z","iopub.execute_input":"2022-05-08T20:25:48.37322Z","iopub.status.idle":"2022-05-08T20:25:48.403179Z","shell.execute_reply.started":"2022-05-08T20:25:48.373169Z","shell.execute_reply":"2022-05-08T20:25:48.402282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Load other modules\nimport matplotlib.pyplot as plt  #Graphics\nimport seaborn as sns\nfrom sklearn.ensemble import RandomForestClassifier  #Random Forest algorithm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import RandomizedSearchCV, GridSearchCV \nfrom sklearn.model_selection import cross_val_score\n#To show graphs within the notebook\n%matplotlib inline \n","metadata":{"_uuid":"e1fcc4988370cc040ab19d6530aa4c721430cacf","_cell_guid":"05c4989c-2779-4cf4-832c-2e8984666f29","execution":{"iopub.status.busy":"2022-05-08T20:25:48.404721Z","iopub.execute_input":"2022-05-08T20:25:48.405212Z","iopub.status.idle":"2022-05-08T20:25:49.751833Z","shell.execute_reply.started":"2022-05-08T20:25:48.404972Z","shell.execute_reply":"2022-05-08T20:25:49.751039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#load the datasets\ntrain = pd.read_csv(\"../input/az-handwritten-alphabets-in-csv-format/A_Z Handwritten Data.csv\")\ntest = pd.read_csv(\"../input/az-handwritten-alphabets-in-csv-format/A_Z Handwritten Data.csv\")\n#train = pd.read_csv(\"../input/digit-recognizer/test.csv\")\n#test = pd.read_csv(\".../input/digit-recognizer/test.csv\")\n","metadata":{"_uuid":"7ebda4490759bacb17c49e287b642d38b78dba21","_cell_guid":"65ab9b16-c6fa-4df2-b0a7-94982aea44f3","execution":{"iopub.status.busy":"2022-05-08T20:25:49.753626Z","iopub.execute_input":"2022-05-08T20:25:49.754216Z","iopub.status.idle":"2022-05-08T20:27:14.606685Z","shell.execute_reply.started":"2022-05-08T20:25:49.754156Z","shell.execute_reply":"2022-05-08T20:27:14.605525Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Printing the size of the dataframe\nprint (\"Training dataset has %i observations and %i variables\" %(train.shape[0], train.shape[1]))\nprint (\"Testing dataset has %i observations and %i variables\" %(test.shape[0], test.shape[1]))","metadata":{"_uuid":"8b389d193143bdc22091824caef9ff0a4696b7a1","_cell_guid":"4cbc258d-7ae5-4b55-9b3a-6f7c6beb53ad","execution":{"iopub.status.busy":"2022-05-08T20:27:14.608541Z","iopub.execute_input":"2022-05-08T20:27:14.608853Z","iopub.status.idle":"2022-05-08T20:27:14.616452Z","shell.execute_reply.started":"2022-05-08T20:27:14.608794Z","shell.execute_reply":"2022-05-08T20:27:14.615406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#check few rows\ntrain.head()","metadata":{"_uuid":"2ed9cf897f026775aa7570062d041e89b02ab46b","_cell_guid":"f72341bc-0775-4658-84ad-d0b0d30fcfed","execution":{"iopub.status.busy":"2022-05-08T20:27:14.617617Z","iopub.execute_input":"2022-05-08T20:27:14.617847Z","iopub.status.idle":"2022-05-08T20:27:14.658185Z","shell.execute_reply.started":"2022-05-08T20:27:14.617806Z","shell.execute_reply":"2022-05-08T20:27:14.657589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Seperate the target and independant variables\ndf_x=train.iloc[:,1:]\ndf_y=train.iloc[:,0]","metadata":{"_uuid":"1623346b812b05b3ea96a93f50a72745f67399ef","_cell_guid":"becde63b-f99a-4267-8297-141ae1376a5a","execution":{"iopub.status.busy":"2022-05-08T20:27:14.659343Z","iopub.execute_input":"2022-05-08T20:27:14.659811Z","iopub.status.idle":"2022-05-08T20:27:14.664848Z","shell.execute_reply.started":"2022-05-08T20:27:14.659767Z","shell.execute_reply":"2022-05-08T20:27:14.66423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def print_image(row, df):\n    temp=df.iloc[row,:].values\n    temp = temp.reshape(28,28).astype('uint8')\n    plt.imshow(temp)","metadata":{"_uuid":"11ffab42a1fcf15630b986a6feab3adcf55ca9c1","_cell_guid":"585f5ac0-7bea-4cde-a84a-6ff1183c5d22","execution":{"iopub.status.busy":"2022-05-08T20:27:14.666177Z","iopub.execute_input":"2022-05-08T20:27:14.666625Z","iopub.status.idle":"2022-05-08T20:27:14.676532Z","shell.execute_reply.started":"2022-05-08T20:27:14.666582Z","shell.execute_reply":"2022-05-08T20:27:14.675805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print_image(1, df_x)","metadata":{"execution":{"iopub.status.busy":"2022-05-08T20:27:14.677715Z","iopub.execute_input":"2022-05-08T20:27:14.678015Z","iopub.status.idle":"2022-05-08T20:27:14.979371Z","shell.execute_reply.started":"2022-05-08T20:27:14.677964Z","shell.execute_reply":"2022-05-08T20:27:14.977708Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print_image(2, df_x)","metadata":{"execution":{"iopub.status.busy":"2022-05-08T20:27:14.98096Z","iopub.execute_input":"2022-05-08T20:27:14.981454Z","iopub.status.idle":"2022-05-08T20:27:15.098704Z","shell.execute_reply.started":"2022-05-08T20:27:14.981396Z","shell.execute_reply":"2022-05-08T20:27:15.097874Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print_image(3, df_x)","metadata":{"_uuid":"890dc2d91329e8b47388baeffaa0205dccfcd3c4","_cell_guid":"ab59e441-2096-452c-bae9-a2a39d6419e2","execution":{"iopub.status.busy":"2022-05-08T20:27:15.100179Z","iopub.execute_input":"2022-05-08T20:27:15.100537Z","iopub.status.idle":"2022-05-08T20:27:15.210233Z","shell.execute_reply.started":"2022-05-08T20:27:15.10046Z","shell.execute_reply":"2022-05-08T20:27:15.209475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Check the frequency of each number\ndf_y.value_counts().sort_index()","metadata":{"_uuid":"55cd55b7752a47c3719c25134b85756269e299bf","_cell_guid":"4c1a85d7-acb5-42d4-8c61-bac3e995cf8e","execution":{"iopub.status.busy":"2022-05-08T20:27:15.211361Z","iopub.execute_input":"2022-05-08T20:27:15.21165Z","iopub.status.idle":"2022-05-08T20:27:15.229555Z","shell.execute_reply.started":"2022-05-08T20:27:15.211606Z","shell.execute_reply":"2022-05-08T20:27:15.228928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.countplot(df_y)","metadata":{"_uuid":"8484f4d88b7c5ccaa772ce76ab1606f9157d708b","_cell_guid":"cb36bb37-82d4-4cd3-ac02-b863cbc62612","execution":{"iopub.status.busy":"2022-05-08T20:27:15.230577Z","iopub.execute_input":"2022-05-08T20:27:15.230975Z","iopub.status.idle":"2022-05-08T20:27:15.466756Z","shell.execute_reply.started":"2022-05-08T20:27:15.230925Z","shell.execute_reply":"2022-05-08T20:27:15.466045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#plt.figure(figsize=(5,25))\n#for i in range(40):\n   # plt.subplot(4, 10, i+1)\n    #print_image(i, test)","metadata":{"_uuid":"234bf61d2611372c497a6ab20447a7694ed1f612","_cell_guid":"43493f2e-bc4d-43de-bca1-112546baf4ed","execution":{"iopub.status.busy":"2022-05-08T20:27:15.468105Z","iopub.execute_input":"2022-05-08T20:27:15.468343Z","iopub.status.idle":"2022-05-08T20:27:15.472101Z","shell.execute_reply.started":"2022-05-08T20:27:15.468301Z","shell.execute_reply":"2022-05-08T20:27:15.471417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Split the dataset\nX_train, X_test, y_train, y_test = train_test_split(df_x, df_y, test_size=0.3, random_state=0)\nprint(X_train.shape)\nprint(X_test.shape)\nlen(X_train)\nlen(X_test)","metadata":{"_uuid":"09ae524c95d0633db7ba745b1afc484273c51949","_cell_guid":"b39f5091-7da1-49e6-b225-e58883a53d67","execution":{"iopub.status.busy":"2022-05-08T20:27:15.47331Z","iopub.execute_input":"2022-05-08T20:27:15.473573Z","iopub.status.idle":"2022-05-08T20:27:18.677882Z","shell.execute_reply.started":"2022-05-08T20:27:15.473523Z","shell.execute_reply":"2022-05-08T20:27:18.677157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#training random Forest\nrf=RandomForestClassifier(n_estimators=50)\nrf.fit(X_train,y_train)","metadata":{"_uuid":"f3ff4001949f010bf1c8ae201b10e10687ff5d7b","_cell_guid":"468d361a-8c3c-44c5-82a1-0f0348bf3f0e","execution":{"iopub.status.busy":"2022-05-08T20:27:18.679288Z","iopub.execute_input":"2022-05-08T20:27:18.679546Z","iopub.status.idle":"2022-05-08T20:29:49.343438Z","shell.execute_reply.started":"2022-05-08T20:27:18.679497Z","shell.execute_reply":"2022-05-08T20:29:49.342695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred=rf.predict(X_test)\nprint (\"Classification Report\")\nprint(classification_report(y_test, pred))\nprint (\"Confusion Report\")\nprint(confusion_matrix(y_test, pred))","metadata":{"_uuid":"43fbbde532db261b201c3298afbcff84f05a0d91","_cell_guid":"75612f96-8bfa-48d1-b741-61ca37760a6c","execution":{"iopub.status.busy":"2022-05-08T20:29:49.344627Z","iopub.execute_input":"2022-05-08T20:29:49.344876Z","iopub.status.idle":"2022-05-08T20:29:54.034315Z","shell.execute_reply.started":"2022-05-08T20:29:49.344819Z","shell.execute_reply":"2022-05-08T20:29:54.033376Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The accuracy is 96%","metadata":{"_uuid":"ae987c70ec76d34a88bd92c641faff7e16031321"}},{"cell_type":"code","source":"#Cross validation\nrf=RandomForestClassifier(n_estimators=100)\nrf.fit(df_x, df_y)\nscore = cross_val_score(rf, df_x, df_y)\nprint (np.mean(score))","metadata":{"_uuid":"69660dba64d1d860910a2c4d2ab6cd462908bad4","_cell_guid":"9e9f4c50-d524-47b8-8d7a-2e75dc6934df","execution":{"iopub.status.busy":"2022-05-08T20:29:54.035754Z","iopub.execute_input":"2022-05-08T20:29:54.036154Z","iopub.status.idle":"2022-05-08T20:48:53.83609Z","shell.execute_reply.started":"2022-05-08T20:29:54.036081Z","shell.execute_reply":"2022-05-08T20:48:53.835087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Predicting on test data\npred= rf.predict(test)","metadata":{"_uuid":"055a0cab3a3b0cdaf73a3a2faf46fddecb2567a2","execution":{"iopub.status.busy":"2022-05-08T20:48:53.837963Z","iopub.execute_input":"2022-05-08T20:48:53.838512Z","iopub.status.idle":"2022-05-08T20:48:55.588056Z","shell.execute_reply.started":"2022-05-08T20:48:53.838454Z","shell.execute_reply":"2022-05-08T20:48:55.534511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred = pd.Series(pred,name=\"Label\")\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),pred],axis = 1)\nsubmission.to_csv(\"mnist_rf.csv\",index=False)","metadata":{"_uuid":"6ad6a931e9754942b30e6f547b492d6a108e3865","execution":{"iopub.status.busy":"2022-05-08T20:48:55.53532Z","iopub.status.idle":"2022-05-08T20:48:55.53562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#IMPORT LIBRARIES\nimport numpy as np\nimport cv2\nfrom keras.models import load_model\nimport imutils\nfrom imutils.contours import sort_contours\n\n#model = load_model('./model_jd_96.h5')\n\n\n\ndef prep_labels():\n  labelNames = \"0123456789\"\n  labelNames += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n  #labelNames += \"abcdefghijklmnopqrstuvwxyz\"\n  labelNames = [l for l in labelNames]\n  return labelNames\n\n\ndef get_image_predict(image_path):\n  image = cv2.imread(image_path)\n  gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n  blurred = cv2.GaussianBlur(gray, (5, 5), 0)\n  # perform edge detection, find contours in the edge map, and sort the\n  # resulting contours from left-to-right\n  edged = cv2.Canny(blurred, 30, 150)\n  cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,\n    cv2.CHAIN_APPROX_SIMPLE)\n  cnts = imutils.grab_contours(cnts)\n  cnts = sort_contours(cnts, method=\"left-to-right\")[0]\n  # initialize the list of contour bounding boxes and associated\n  # characters that we'll be OCR'ing\n  chars = []\n  # loop over the contours\n  for c in cnts:\n    # compute the bounding box of the contour\n    (x, y, w, h) = cv2.boundingRect(c)\n    # filter out bounding boxes, ensuring they are neither too small\n    # nor too large\n    if (w >= 15 and w <= 150) and (h >= 8 and h <= 200):\n      # extract the character and threshold it to make the character\n      # appear as *white* (foreground) on a *black* background, then\n      # grab the width and height of the thresholded image\n      roi = gray[y:y + h, x:x + w]\n      thresh = cv2.threshold(roi, 0, 255,\n        cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]\n      (tH, tW) = thresh.shape\n      # if the width is greater than the height, resize along the\n      # width dimension\n      if tW > tH:\n        thresh = imutils.resize(thresh, width=30)\n      # otherwise, resize along the height\n      else:\n        thresh = imutils.resize(thresh, height=30)\n          # re-grab the image dimensions (now that its been resized)\n      # and then determine how much we need to pad the width and\n      # height such that our image will be 32x32\n      (tH, tW) = thresh.shape\n      dX = int(max(0, 30 - tW) / 2.0)\n      dY = int(max(0, 30 - tH) / 2.0)\n      # pad the image and force 32x32 dimensions\n      padded = cv2.copyMakeBorder(thresh, top=dY, bottom=dY,\n        left=dX, right=dX, borderType=cv2.BORDER_CONSTANT,\n        value=(0, 0, 0))\n      padded = cv2.resize(padded, (30, 30))\n      # prepare the padded image for classification via our\n      # handwriting OCR model\n      padded = padded.astype(\"float32\") / 255.0\n      padded = np.expand_dims(padded, axis=-1)\n      # update our list of characters that will be OCR'd\n      chars.append((padded, (x, y, w, h)))\n    # extract the bounding box locations and padded characters\n  boxes = [b[1] for b in chars]\n  chars = np.array([c[0] for c in chars], dtype=\"float32\")\n  # OCR the characters using our handwriting recognition model\n  preds = rf.predict(chars)\n  word = []\n  for (pred, (x, y, w, h)) in zip(preds, boxes):\n\t# find the index of the label with the largest corresponding\n\t# probability, then extract the probability and label\n    i = np.argmax(pred)\n    prob = pred[i]\n    label = prep_labels()[i]\n    word.append(label)\n    # draw the prediction on the image\n    print(\"[INFO] {} - {:.2f}%\".format(label, prob * 100))\n    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)\n    cv2.putText(image, label, (x - 10, y - 10),\n      cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 2)\n    # show the image\n    #cv2.imshow(\"Image\", image)\n    #cv2.waitKey(0)\n    output = ''.join(map(str, word))\n  return image,output\n\noutput_image, output_text = get_image_predict('../input/Arpitha/arpitha.jpeg') \nprint(\"Digitalized text: \", output_text)\ncv2.imshow(output_image)\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install imutils","metadata":{"execution":{"iopub.status.busy":"2022-05-08T22:25:54.265457Z","iopub.execute_input":"2022-05-08T22:25:54.265757Z","iopub.status.idle":"2022-05-08T22:25:54.271076Z","shell.execute_reply.started":"2022-05-08T22:25:54.265706Z","shell.execute_reply":"2022-05-08T22:25:54.270122Z"},"trusted":true},"execution_count":null,"outputs":[]}]}