{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\nlis = []\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        lis.append(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport PIL.Image as image\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport seaborn as sns\nfrom plotly.offline import iplot, plot, init_notebook_mode\nimport plotly.graph_objs as go\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\nimport plotly.figure_factory as ff\nimport tqdm\nimport warnings","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_IMGS = '/kaggle/input/cassava-leaf-disease-classification/train_images/'\nTEST_IMGS = '/kaggle/input/cassava-leaf-disease-classification/test_images/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"warnings.filterwarnings('ignore')\ninit_notebook_mode('connected')\nplt.rcParams['figure.figsize'] = [12,6]\ntqdm.tqdm.pandas()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/cassava-leaf-disease-classification/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['label_names']=np.select(choicelist=[\"Cassava Bacterial Blight (CBB)\",\n                                              \"Cassava Brown Streak Disease (CBSD)\", \n                                              \"Cassava Green Mottle (CGM)\", \n                                              \"Cassava Mosaic Disease (CMD)\",\n                                              \"Healthy\"],\n                                 condlist=[train_df['label']==0,\n                                           train_df['label']==1,\n                                           train_df['label']==2,\n                                           train_df['label']==3,\n                                           train_df['label']==4])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.subplot(1, 2, 1).figure\n# fig.set_figheight(10)\n# fig.set_figwidth(25)\nsns.countplot('label_names', data = train_df)\nplt.title('Count of label names', fontdict={'size':20, 'color':'white'})\nplt.tick_params(labelrotation=90, labelsize = 15, axis = 'x')\nplt.tick_params(labelcolor='white', axis = 'y')\n\n\n# ax.set_figheight(10)\n\nplt.subplot(1, 2, 2)\nsns.countplot('label', data = train_df)\nplt.title('Count of label', fontdict = {'size':20, 'color':'white'})\nplt.tick_params(labelsize = 15, labelcolor='white', axis = 'x')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def display_images(label, rows=2, cols = 2, image = False):\n    images = train_df[train_df['label'] == label]['image_id'].sample(rows*cols).values\n    fig, ax = plt.subplots(nrows = rows, ncols = cols, figsize= (15, 10))\n    ax = ax.flatten()\n    for i in range(len(images)):\n        quick = cv2.imread(TRAIN_IMGS+images[i])\n        quick = cv2.cvtColor(quick, cv2.COLOR_BGR2RGB)\n        ax[i].imshow(quick)\n        ax[i].set_title(train_df[train_df['label']==label]['label_names'].head(1).values[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display_images(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display_images(1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display_images(2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display_images(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display_images(4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def color_channels(label):\n    img_details = train_df[train_df['label']==label].sample(1).values\n    quick = cv2.imread(TRAIN_IMGS+img_details[:, 0][0])\n    quick = cv2.cvtColor(quick, cv2.COLOR_BGR2RGB)\n    fig = make_subplots(1, 2)\n    red = go.Histogram({'x': cv2.calcHist(quick, [0], None, [255], [0, 255]).reshape(-1), 'text':'Red', 'marker':{'color':'red'}, 'name':'Red', 'xbins':{'size':1}})\n    green = go.Histogram({'x':cv2.calcHist(quick, [1], None, [255], [0, 255]).reshape(-1), 'text':'Green', 'marker':{'color':'green'}, 'name':'Green', 'xbins':{'size':1}})\n    blue = go.Histogram({'x':cv2.calcHist(quick, [2], None, [255], [0, 255]).reshape(-1), 'text':'Blue', 'marker':{'color':'blue'}, 'name':'Blue', 'xbins':{'size':1}})\n    fig.add_trace(red, row =1, col=2)\n    fig.add_trace(green, row= 1, col=2)\n    fig.add_trace(blue, row = 1, col=2)\n    fig.add_trace(go.Image({'name' : img_details[:, 2][0]}, z = quick ))\n    layout = {'title':'Color channel Histogram', 'barmode':'stack', 'template':'simple_white'}\n    fig.update_layout(layout)\n    # fig = go.Figure(data = data, layout=layout)\n    iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"color_channels(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"color_channels(1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"color_channels(2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"color_channels(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"color_channels(4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"dat = train_df.head(1)\nquick = cv2.imread(TRAIN_IMGS+dat.values[:, 0][0])\nquick = cv2.cvtColor(quick, cv2.COLOR_BGR2RGB)\nfig = make_subplots(rows=2, cols = 2)\nfig2 = ff.create_distplot([quick[:, :, 0][0]], ['Red'], colors=['red'])\nfig3  = ff.create_distplot([quick[:, :, 1][0]], ['Green'], colors = ['green'])\nfig4 = ff.create_distplot([quick[:, :, 2][0]], ['Blue'], colors = ['blue'])\nfig.add_trace(go.Histogram(fig2['data'][0]), row = 1, col = 1)\nfig.add_trace(go.Scatter(fig2['data'][1]), row = 1, col = 1)\nfig.add_trace(go.Histogram(fig3['data'][0]), row=1, col = 2)\nfig.add_trace(go.Scatter(fig3['data'][1]), row = 1, col=2)\nfig.add_trace(go.Histogram(fig4['data'][0]), row = 2, col = 1)\nfig.add_trace(go.Scatter(fig4['data'][1]), row = 2, col = 1)\nlayout = dict(title = \"Distribution of Color channel values in %s.\" %dat.values[:, 0][0])\nfig.update_layout(layout)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# test=ImageDataGenerator(rescale=1/255).flow_from_dataframe(train_df.head(100),\n#                                                            TRAIN_IMGS, x_col='image_id',\n#                                                            y_col = 'label', class_mode='raw',\n#                                                            shuffle=False, batch_size=100, target_size = (600, 800))\n# train_images = test[0][0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_image(image_id):\n    image = cv2.imread(TRAIN_IMGS + image_id)\n    return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    \ntrain_images = train_df[\"image_id\"][:100].progress_apply(load_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"red_values = [np.mean(train_images[idx][:, :, 0]) for idx in range(len(train_images))]\ngreen_values = [np.mean(train_images[idx][:, :, 1]) for idx in range(len(train_images))]\nblue_values = [np.mean(train_images[idx][:, :, 2]) for idx in range(len(train_images))]\nvalues = [np.mean(train_images[idx]) for idx in range(len(train_images))]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"fig = make_subplots(rows=2, cols = 2)\n# trace1 = dict(x = values,  = 'Channels', text = 'Channels', marker = dict(color='purple'))\nvals = ff.create_distplot([values], group_labels=['Channels'], colors=['purple'])\nreds  = ff.create_distplot([red_values], group_labels=['Red Values'], colors = ['red'])\ngreens = ff.create_distplot([green_values], group_labels=['Green Values'], colors = ['green'])\nblues = ff.create_distplot([blue_values], group_labels = ['Blue Values'], colors = ['blue'])\n\nfig.add_trace(vals['data'][0], row=1, col = 1)\nfig.add_trace(vals['data'][1], row = 1, col = 1)\nfig.add_trace(reds['data'][0], row = 1, col = 2)\nfig.add_trace(reds['data'][1], row = 1, col = 2)\nfig.add_trace(greens['data'][0], row=2, col = 1)\nfig.add_trace(greens['data'][1], row = 2, col = 1)\nfig.add_trace(blues['data'][0], row = 2, col= 2)\nfig.add_trace(blues['data'][1], row = 2, col = 2)\n\nfig.update_traces({'marker':{'line':{'width':0.3}}})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trace1 = dict(y = red_values, type = 'box', name = 'Red', marker = dict(color = 'red'), text = 'Red values')\ntrace2 = dict(y = green_values, type = 'box', name = 'Green', marker = dict(color = 'green'), text = 'Green values')\ntrace3 = dict(y = blue_values, type = 'box', name = 'Blue', marker = dict(color = 'blue'), text = 'Blue values')\nfig = go.Figure()\nfig.add_trace(trace1)\nfig.add_trace(trace2)\nfig.add_trace(trace3)\nlayout = dict(title = 'Color values box plot')\nfig.update_layout(layout)\n\niplot(fig)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Blurring"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.subplot(1, 2, 1)\nfig.figure.set_figheight(30)\nfig.figure.set_figwidth(30)\nplt.imshow(train_images[0])\nplt.title('Normal Image', fontdict={'size':30})\n\nkernel = np.ones((5, 5), dtype = np.float32)/22\nimg = cv2.filter2D(train_images[0], -1,kernel)\nplt.subplot(1, 2, 2)\nplt.imshow(img)\nplt.title('Image blurred using filter2D with kernel', fontdict={'size':30})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.subplot(1, 2, 1)\nfig.figure.set_figheight(30)\nfig.figure.set_figwidth(30)\nplt.imshow(train_images[99])\nplt.title('Normal Image', fontdict={'size':30})\n\n\nplt.subplot(1, 2, 2)\nplt.imshow(cv2.blur(train_images[99], (5, 5)))\nplt.title('Image blurred using blur', fontdict = {'size':30})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.subplot(1, 2, 1)\nfig.figure.set_figheight(30)\nfig.figure.set_figwidth(30)\nplt.imshow(train_images[27])\nplt.title('Normal Image', fontdict={'size':30})\n\nplt.subplot(1, 2, 2)\nplt.imshow(cv2.GaussianBlur(train_images[27], (5, 5), 10))\nplt.title('Image blurred using GaussianBlur', fontdict = {'size':30})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.subplot(1, 2, 1)\nfig.figure.set_figheight(30)\nfig.figure.set_figwidth(30)\nplt.imshow(train_images[69])\nplt.title('Normal Image', fontdict = {'size':20})\n\nplt.subplot(1, 2, 2)\nplt.imshow(cv2.medianBlur(train_images[69], 5))\nplt.title('Image blurred using medianBlurr', fontdict = {'size':20})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.subplot(1, 2, 1)\nfig.figure.set_figheight(30)\nfig.figure.set_figwidth(30)\nplt.imshow(train_images[20])\nplt.title('Normal Image', fontdict = {'size':20})\n\nplt.subplot(1, 2, 2)\nplt.imshow(cv2.bilateralFilter(train_images[20], 11, 75, 75))\nplt.title('Image blurred using bilateralFilter');","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Blending"},{"metadata":{"trusted":true},"cell_type":"code","source":"sticker = cv2.resize(train_images[10], (250, 250))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (12, 5))\nplt.imshow(train_images[11])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Overlaying images of different sizes\ncopy = train_images[11].copy()\ncopy[350:, 550:] = sticker","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (12, 6))\nplt.imshow(copy)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#using addFilter\nprint(train_images[10].shape)\nprint(train_images[11].shape)\n\nplt.figure(figsize = (10, 6))\nplt.imshow(cv2.addWeighted(train_images[10], 0.6, train_images[11], 0.6, 0.3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Blending images of different sizes\nsticker = cv2.imread('/kaggle/input/opencv-practice-zip/computer-vision-with-python/Computer-Vision-with-Python/DATA/watermark_no_copy.png')\nsticker = cv2.cvtColor(sticker, cv2.COLOR_BGR2RGB) \nplt.imshow(sticker)\nprint(sticker.shape)\n\nsticker = cv2.resize(sticker, (250, 250))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Blending images of different sizes\ngray_sticker = cv2.cvtColor(sticker, cv2.COLOR_RGB2GRAY)\nmask_inv = cv2.bitwise_not(gray_sticker)\nwhite_background = np.full(sticker.shape, 255, dtype=np.uint8)\nfg = cv2.bitwise_or(sticker, sticker, mask = mask_inv)\nroi = train_images[12][:250, :250]\ntrain_images[12][:250, :250]= cv2.bitwise_or(roi, fg)\n\nplt.figure(figsize=(12, 6))\nplt.imshow(train_images[12])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Gradiets\nsobel_x = cv2.Sobel(cv2.cvtColor(train_images[11], cv2.COLOR_RGB2GRAY), None, 1, 0, (7, 7))\nsobel_y = cv2.Sobel(cv2.cvtColor(train_images[11], cv2.COLOR_RGB2GRAY), None, 0, 1, (7, 7))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (10, 6))\nplt.imshow(cv2.addWeighted(sobel_x, 0.6, sobel_y, 0.6, 0.5), cmap = 'gray')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Thresholding"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.subplot(1, 2, 1)\nfig.figure.set_figheight(30)\nfig.figure.set_figwidth(30)\nplt.imshow(train_images[69])\nplt.title('Normal Image', fontdict = {'size':20})\n\n\nplt.subplot(1, 2, 2)\nret, thresh_img = cv2.threshold(cv2.cvtColor(train_images[69], cv2.COLOR_RGB2GRAY), 120, 255, cv2.THRESH_BINARY)\nplt.imshow(thresh_img, cmap = 'gray')\nplt.title('Thresholded image using THRESH_BINARY', fontdict = {'size':20})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.subplot(1, 2, 1)\nfig.figure.set_figheight(30)\nfig.figure.set_figwidth(30)\nplt.imshow(train_images[69])\nplt.title('Normal Image', fontdict = {'size':20})\n\n\nplt.subplot(1, 2, 2)\nret, thresh_img = cv2.threshold(cv2.cvtColor(train_images[69], cv2.COLOR_RGB2GRAY), 120, 255, cv2.THRESH_BINARY_INV)\nplt.imshow(thresh_img, cmap = 'gray')\nplt.title('Thresholded image using THRESH_BINARY_INV', fontdict = {'size':20})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.subplot(1, 2, 1)\nfig.figure.set_figheight(30)\nfig.figure.set_figwidth(30)\nplt.imshow(train_images[69])\nplt.title('Normal Image', fontdict = {'size':20})\n\n\nplt.subplot(1, 2, 2)\nret, thresh_img = cv2.threshold(cv2.cvtColor(train_images[69], cv2.COLOR_RGB2GRAY), 120, 255, cv2.THRESH_TOZERO)\nplt.imshow(thresh_img, cmap = 'gray')\nplt.title('Thresholded image using THRESH_TOZERO', fontdict = {'size':20})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.subplot(1, 2, 1)\nfig.figure.set_figheight(30)\nfig.figure.set_figwidth(30)\nplt.imshow(train_images[69])\nplt.title('Normal Image', fontdict = {'size':20})\n\n\nplt.subplot(1, 2, 2)\nret, thresh_img = cv2.threshold(cv2.cvtColor(train_images[69], cv2.COLOR_RGB2GRAY), 120, 255, cv2.THRESH_TOZERO_INV)\nplt.imshow(thresh_img, cmap = 'gray')\nplt.title('Thresholded image using THRESH_TOZERO_INV', fontdict = {'size':20})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.subplot(1, 2, 1)\nfig.figure.set_figheight(30)\nfig.figure.set_figwidth(30)\nplt.imshow(train_images[69])\nplt.title('Normal Image', fontdict = {'size':20})\n\n\nplt.subplot(1, 2, 2)\nret, thresh_img = cv2.threshold(cv2.cvtColor(train_images[69], cv2.COLOR_RGB2GRAY), 120, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)\nplt.imshow(thresh_img, cmap = 'gray')\nplt.title('Thresholded image using THRESH_TOZERO', fontdict = {'size':20})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Morphology"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Create a black Blank image\nblank_img = np.zeros((1080, 1920))\n#Add text ABCDE to blank image\ncv2.putText(blank_img, \"Daimond Hands\", (350, 600), cv2.FONT_HERSHEY_SIMPLEX,5, (255, 255, 255), 25, cv2.LINE_AA)\n\nplt.imshow(blank_img, cmap = 'gray')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Erode foreground\nkernel = np.ones((5, 5), np.uint8)\nplt.imshow(cv2.erode(blank_img, kernel, iterations = 3), cmap = 'gray')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Remove White Noise\nwhite_noise = np.random.randint(0, 2, (1080, 1920))\nwhite_noise = white_noise*255\nimg = blank_img.copy()\nnoise_img = img + white_noise\n\n\nplt.subplot(1, 2, 1)\nplt.imshow(noise_img, cmap = 'gray')\nplt.title('Noisy Image')\n\n\nplt.subplot(1, 2, 2)\nplt.imshow(cv2.morphologyEx(noise_img.astype('uint8'), cv2.MORPH_OPEN, kernel), cmap = 'gray')\nplt.title('De-Noised Image')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"black_noise = np.random.randint(0, 2, (1080, 1920))\nblack_noise = black_noise*-255\nnoise_img = img + black_noise\nnoise_img[noise_img==-255] = 0\n\nplt.subplot(1, 2, 1)\nplt.imshow(noise_img, cmap = 'gray')\nplt.title('Noisy image')\n\nplt.subplot(1, 2, 2)\nplt.imshow(cv2.morphologyEx(noise_img, cv2.MORPH_CLOSE, kernel), cmap = 'gray')\nplt.title('De-Noised image');","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.subplot(1, 2, 1)\nplt.imshow(img, cmap = 'gray')\nplt.title('Noisy, image')\n\nplt.subplot(1, 2, 2)\nplt.imshow(cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel), cmap = 'gray')\nplt.title('Hollowed image')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Corner Detection"},{"metadata":{"trusted":true},"cell_type":"code","source":"chess = cv2.imread('/kaggle/input/opencv-practice-zip/computer-vision-with-python/Computer-Vision-with-Python/DATA/flat_chessboard.png')\nchess = cv2.cvtColor(chess, cv2.COLOR_BGR2RGB)\nplt.subplot(1, 2, 1)\nplt.imshow(chess)\n\nret, corners = cv2.findChessboardCorners(chess, (7, 7))\nplt.subplot(1, 2, 2)\ncopy = chess.copy()\nplt.imshow(cv2.drawChessboardCorners(copy, (7, 7), corners, ret));","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Finding corners of corner harris algorithm\ndst = cv2.cornerHarris(cv2.cvtColor(train_images[12], cv2.COLOR_RGB2GRAY), 3, 3, 0.01)\n\ndst = cv2.dilate(dst, None)\ncopy = train_images[12].copy()\ncopy[dst>0.06*dst.max()] = [255, 0, 0]\n\nplt.imshow(copy);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Finding corners using corner harris algorithm\ndst = cv2.cornerHarris(cv2.cvtColor(chess, cv2.COLOR_RGB2GRAY), 3, 3, 0.1)\n\ndst = cv2.dilate(dst, None)\n\ncopy = chess.copy()\n\ncopy[dst>0.06*dst.max()] = [255, 0, 0]\n\nplt.imshow(copy);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Find corners using goodFeaturesToTrack(Shi Tomasi algorithm)\n\ncorners = cv2.goodFeaturesToTrack(cv2.cvtColor(chess, cv2.COLOR_RGB2GRAY), 50, 0.01, 4, 10, None)\n\ncorners = np.int0(corners)\ncopy = chess.copy()\nfor i in corners:\n    x, y = i.ravel()\n    cv2.circle(copy, (x, y), 3, 255, -1)\nplt.imshow(copy);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Find corners using goodFeaturesToTrack(Shi Tomasi algorithm)\n\ncopy = train_images[42].copy()\ncorners = cv2.goodFeaturesToTrack(cv2.cvtColor(copy, cv2.COLOR_RGB2GRAY), 30, 0.06, 3)\n\ncorners = np.int0(corners)\n\nfor i in corners:\n    x, y = i.ravel()\n    cv2.circle(copy, (x, y), 10, 255, -1)\n    \nplt.imshow(copy)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Edge Detection"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Canny Edge detection\nfig = plt.subplot(1, 2, 1)\n# fig.figure.set_figheight(50)\n# fig.figure.set_figwidth(50)\nplt.imshow(train_images[0])\nplt.subplot(1, 2, 2)\nplt.imshow(cv2.Canny(train_images[0], 100, 200), cmap= 'gray')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Canny Edge detection after blurring\nfig = plt.subplot(1, 3, 1)\nfig.figure.set_figheight(20)\nfig.figure.set_figwidth(20)\nplt.imshow(train_images[0])\nplt.title('Normal image')\n\ncopy = train_images[0].copy()\n\nblurred = cv2.GaussianBlur(copy, (7, 7), 10)\nplt.subplot(1, 3, 2)\nplt.imshow(blurred)\nplt.title('Blurred image')\n\nplt.subplot(1, 3, 3)\nplt.imshow(cv2.Canny(blurred, 100, 200))\nplt.title('Edges after blurring')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Grid detection\ndots = cv2.imread('/kaggle/input/opencv-practice-zip/computer-vision-with-python/Computer-Vision-with-Python/DATA/dot_grid.png')\n# dots = cv2.cvtColor(dots, cv2.COLOR_BGR2RGB)\nplt.imshow(dots)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Grid detection\nret, corners = cv2.findCirclesGrid(dots, (10, 10), cv2.CALIB_CB_SYMMETRIC_GRID)\ncopy = dots.copy()\nplt.imshow(cv2.drawChessboardCorners(copy, (10, 10), corners, ret))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Contour detection"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Contour detection using findContours\nimg = cv2.imread('/kaggle/input/opencv-practice-zip/Computer-Vision-with-Python/DATA/internal_external.png', 0)\nplt.imshow(img, cmap = 'gray')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#External Contours\ncontours, hierarchy = cv2.findContours(img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)\n\nexternal_countours = np.zeros(img.shape)\n\nfor i in range(len(contours)):\n    if hierarchy[0][i][3] == -1:\n        cv2.drawContours(external_countours, contours, i, 255, 5)\n        \nplt.imshow(external_countours, cmap = 'gray')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Internal Contours\ninternal_contours = np.zeros(img.shape)\nfor i in range(len(contours)):\n    if hierarchy[0][i][3] != -1:\n        cv2.drawContours(internal_contours, contours, i, 255, -1)\n        \nplt.imshow(internal_contours, cmap= 'gray')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"contours, hierarchy = cv2.findContours(cv2.cvtColor(train_images[69], cv2.COLOR_RGB2GRAY), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)\n\nexternal_countours = np.zeros(train_images[69].shape)\n\nfor i in range(len(contours)):\n    if hierarchy[0][i][3] == -1:\n        cv2.drawContours(external_countours, contours, i, 255, 5)\n        \nplt.imshow(external_countours)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Feature Matching"},{"metadata":{"trusted":true},"cell_type":"code","source":"img1 = train_images[10]\nimg2 = train_images[14]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(img1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(img2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Brute Force detection with ORB descreptors\norb = cv2.ORB_create()\n\nkp1, des1 = orb.detectAndCompute(img1, None)\nkp2, des2 = orb.detectAndCompute(img2, None)\n\nbf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck = True)\n\nmatches = bf.match(des1, des2)\n\nmatches = sorted(matches , key = lambda x:x.distance)\n\nimg1_matches = cv2.drawMatches(img1, kp1, img2, kp2, matches[:10], None, flags = 2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(img1_matches)\nplt.title('ORB feature detection')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Brute Force detection with SIFT Descriptors and Ratio Test\nsift = cv2.SIFT_create()\n\nkp1, des1 = sift.detectAndCompute(img1, None)\nkp2, des2 = sift.detectAndCompute(img2, None)\n\nbf = cv2.BFMatcher()\n\nmatches = bf.knnMatch(des1, des2, k = 2)\n\ngood = []\n\nfor match1, match2 in matches:\n    if match1.distance < 0.75*match2.distance:\n        good.append([match1])\nsift_matches = cv2.drawMatchesKnn(img1, kp1, img2, kp2, good, None, flags=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(sift_matches)\nplt.title('SIFT Descriptors')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sift = cv2.SIFT_create()\n\nkp1, des1 = sift.detectAndCompute(img1, None)\nkp2, des2 = sift.detectAndCompute(img2, None)\n\nFLANN_INDEX_KDTREE = 0\nindex_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\nsearch_params = dict(checks = 50)\n\nflann = cv2.FlannBasedMatcher(index_params, search_params)\n\nmatches = flann.knnMatch(des1, des2, k = 2)\n\ngood = []\n\nfor i, (match1, match2) in enumerate(matches):\n    if match1.distance < 0.7* match2.distance:\n        good.append(match1)\n    \nflann_matches = cv2.drawMatches(img1, kp1, img2, kp2, good, None, flags=2)\n\nplt.imshow(flann_matches)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}