{"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":"# # Don't worry about this cell variables, they are just forecasting future results..\n# plt.figure(figsize=(24,12))\n# plt.imshow(np.hstack([im1/255.0, im2, im4/255.0, im5/255.0]))","metadata":{"execution":{"iopub.status.busy":"2022-04-30T09:15:11.091732Z","iopub.execute_input":"2022-04-30T09:15:11.092167Z","iopub.status.idle":"2022-04-30T09:15:11.116717Z","shell.execute_reply.started":"2022-04-30T09:15:11.092030Z","shell.execute_reply":"2022-04-30T09:15:11.115895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Loading data & forecasting","metadata":{}},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport matplotlib.pyplot as plt\nimport cv2\n\nfrom tqdm import tqdm\nimport os","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2022-04-30T09:15:11.118140Z","iopub.execute_input":"2022-04-30T09:15:11.119269Z","iopub.status.idle":"2022-04-30T09:15:11.341470Z","shell.execute_reply.started":"2022-04-30T09:15:11.119196Z","shell.execute_reply":"2022-04-30T09:15:11.340211Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/humpback-whale-identification/train.csv')\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-30T09:15:11.342861Z","iopub.execute_input":"2022-04-30T09:15:11.343102Z","iopub.status.idle":"2022-04-30T09:15:11.422227Z","shell.execute_reply.started":"2022-04-30T09:15:11.343071Z","shell.execute_reply":"2022-04-30T09:15:11.421074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load(path, size=128):\n    img= cv2.resize(cv2.imread(path),(size,size))\n    return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\ndef show():\n    f, ax = plt.subplots(3, 5, figsize=(40,20))\n    for i in tqdm(range(15)):\n        path= os.path.join('../input/humpback-whale-identification/train', df.Image[i])\n        img_id= df.Id[i]\n        ax[i//5][i%5].imshow(load(path, 300), aspect='auto')\n        ax[i//5][i%5].set_title(img_id)\n        ax[i//5][i%5].set_xticks([]); ax[i//5][i%5].set_yticks([])\n    plt.show()\n    \nshow()","metadata":{"execution":{"iopub.status.busy":"2022-04-30T09:15:11.425565Z","iopub.execute_input":"2022-04-30T09:15:11.425912Z","iopub.status.idle":"2022-04-30T09:15:14.317877Z","shell.execute_reply.started":"2022-04-30T09:15:11.425861Z","shell.execute_reply":"2022-04-30T09:15:14.316790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Adaptive histogram equalization technique","metadata":{}},{"cell_type":"code","source":"def adaptive_hist(img, clipLimit= 4.0):\n    window= cv2.createCLAHE(clipLimit= clipLimit, tileGridSize=(8, 8))\n    img_lab = cv2.cvtColor(img, cv2.COLOR_BGR2Lab)\n\n    ch1, ch2, ch3 = cv2.split(img_lab)\n    img_l = window.apply(ch1)\n    img_clahe = cv2.merge((img_l, ch2, ch3))\n    return cv2.cvtColor(img_clahe, cv2.COLOR_Lab2BGR)\n\n\ndef show_adhist(clipLimit=4.0):\n    f, ax = plt.subplots(3, 5, figsize=(40,20))\n    for i in tqdm(range(15)):\n        path= os.path.join('../input/humpback-whale-identification/train', df.Image[i])\n        img_id= df.Id[i]\n        img=load(path, 300)\n        img= adaptive_hist(img, clipLimit)\n        ax[i//5][i%5].imshow(img, aspect='auto')\n        ax[i//5][i%5].set_title(img_id)\n        ax[i//5][i%5].set_xticks([]); ax[i//5][i%5].set_yticks([])\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-30T09:15:14.319719Z","iopub.execute_input":"2022-04-30T09:15:14.320282Z","iopub.status.idle":"2022-04-30T09:15:14.335645Z","shell.execute_reply.started":"2022-04-30T09:15:14.320231Z","shell.execute_reply":"2022-04-30T09:15:14.334486Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_adhist(2.0)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T09:15:14.337447Z","iopub.execute_input":"2022-04-30T09:15:14.337993Z","iopub.status.idle":"2022-04-30T09:15:16.918695Z","shell.execute_reply.started":"2022-04-30T09:15:14.337939Z","shell.execute_reply":"2022-04-30T09:15:16.916909Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Color Quantization using K-Means","metadata":{}},{"cell_type":"code","source":"from sklearn.cluster import KMeans","metadata":{"execution":{"iopub.status.busy":"2022-04-30T09:15:16.920995Z","iopub.execute_input":"2022-04-30T09:15:16.921467Z","iopub.status.idle":"2022-04-30T09:15:18.368102Z","shell.execute_reply.started":"2022-04-30T09:15:16.921391Z","shell.execute_reply":"2022-04-30T09:15:18.366920Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def k_means(img, n_colors= 4):\n    w, h, d = original_shape = tuple(img.shape)\n    img= img/255.0\n    image_array = np.reshape(img, (w * h, d))\n    kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array)\n    labels = kmeans.predict(image_array)\n    \n    \"\"\"Recreate the (compressed) image from the code book & labels\"\"\"\n    codebook= kmeans.cluster_centers_\n    d = codebook.shape[1]\n    image = np.zeros((w, h, d))\n    label_idx = 0\n    for i in range(w):\n        for j in range(h):\n            image[i][j] = codebook[labels[label_idx]]\n            label_idx += 1\n    return image","metadata":{"execution":{"iopub.status.busy":"2022-04-30T09:15:18.369639Z","iopub.execute_input":"2022-04-30T09:15:18.369902Z","iopub.status.idle":"2022-04-30T09:15:18.380563Z","shell.execute_reply.started":"2022-04-30T09:15:18.369869Z","shell.execute_reply":"2022-04-30T09:15:18.378995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def show_kmean(n_colors=4):\n    f, ax = plt.subplots(3, 5, figsize=(40,20))\n    for i in tqdm(range(15)):\n        path= os.path.join('../input/humpback-whale-identification/train', df.Image[i])\n        img_id= df.Id[i]\n        img=load(path, 300)\n        img= k_means(img , n_colors= n_colors)\n        ax[i//5][i%5].imshow(img, aspect='auto')\n        ax[i//5][i%5].set_title(img_id)\n        ax[i//5][i%5].set_xticks([]); ax[i//5][i%5].set_yticks([])\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-30T09:15:18.383073Z","iopub.execute_input":"2022-04-30T09:15:18.383516Z","iopub.status.idle":"2022-04-30T09:15:18.399989Z","shell.execute_reply.started":"2022-04-30T09:15:18.383475Z","shell.execute_reply":"2022-04-30T09:15:18.398807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_kmean(n_colors= 4)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T09:15:18.401893Z","iopub.execute_input":"2022-04-30T09:15:18.402218Z","iopub.status.idle":"2022-04-30T09:15:49.697732Z","shell.execute_reply.started":"2022-04-30T09:15:18.402185Z","shell.execute_reply":"2022-04-30T09:15:49.695807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Edge detection with required Morphological Transformations","metadata":{}},{"cell_type":"code","source":"def show_edges(n_colors=4):\n    f, ax = plt.subplots(3, 5, figsize=(40,20))\n    for i in tqdm(range(15)):\n        path= os.path.join('../input/humpback-whale-identification/train', df.Image[i])\n        img_id= df.Id[i]\n        img=load(path, 300)\n        img= k_means(img , n_colors= n_colors)\n        \n        img_gray= cv2.cvtColor(np.uint8(img*255), cv2.COLOR_RGB2GRAY)\n        img_gray= cv2.medianBlur(img_gray,5)\n        edges = cv2.Canny(img_gray,100,200)\n        ax[i//5][i%5].imshow(edges, aspect='auto')\n        ax[i//5][i%5].set_title(img_id)\n        ax[i//5][i%5].set_xticks([]); ax[i//5][i%5].set_yticks([])\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-30T09:15:49.699929Z","iopub.execute_input":"2022-04-30T09:15:49.700190Z","iopub.status.idle":"2022-04-30T09:15:49.710435Z","shell.execute_reply.started":"2022-04-30T09:15:49.700158Z","shell.execute_reply":"2022-04-30T09:15:49.709671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_edges(n_colors =3)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T09:15:49.711877Z","iopub.execute_input":"2022-04-30T09:15:49.712313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Object detection(Drawing bounding boxes around target)","metadata":{}},{"cell_type":"code","source":"def find_box(edges):\n    #contour masking\n    co, hi = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n    con=max(co,key=cv2.contourArea)\n    conv_hull=cv2.convexHull(con)\n    \n    top=tuple(conv_hull[conv_hull[:,:,1].argmin()][0])\n    bottom=tuple(conv_hull[conv_hull[:,:,1].argmax()][0])\n    left=tuple(conv_hull[conv_hull[:,:,0].argmin()][0])\n    right=tuple(conv_hull[conv_hull[:,:,0].argmax()][0])\n    \n    return top, bottom, left, right\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def draw_bound_box():\n    f, ax = plt.subplots(3, 5, figsize=(40,20))\n    for i in tqdm(range(15)):\n        path= os.path.join('../input/humpback-whale-identification/train', df.Image[i])\n        img_id= df.Id[i]\n        img=load(path, 300)\n        org=img.copy()\n        img= k_means(img , n_colors= 10)\n        \n        img_gray= cv2.cvtColor(np.uint8(img*255), cv2.COLOR_RGB2GRAY)\n        img_gray= cv2.medianBlur(img_gray,7)\n        edges = cv2.Canny(img_gray,100,200)\n        \n        kernel= cv2.getStructuringElement(cv2.MORPH_RECT,(15,15))\n        edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)\n        \n        top,bottom,left,right = find_box(edges)\n        org=cv2.rectangle(org, (left[0], top[1]), (right[0], bottom[1]), (0, 255, 0), thickness=3)\n        \n        ax[i//5][i%5].imshow(org, aspect='auto')\n        ax[i//5][i%5].set_title(img_id)\n        ax[i//5][i%5].set_xticks([]); ax[i//5][i%5].set_yticks([])\n    plt.show()\n    ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"    \ndraw_bound_box()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Foreground extraction","metadata":{}},{"cell_type":"code","source":"def forgrd_ext(img, rec):\n    mask= np.zeros(img.shape[:2], np.uint8)\n    bgmodel= np.zeros((1, 65), np.float64)\n    fgmodel= np.zeros((1, 65), np.float64)\n    cv2.grabCut(img, mask, rec, bgmodel, fgmodel, 3, cv2.GC_INIT_WITH_RECT)\n    mask2= np.where((mask==2)|(mask==0), 0, 1).astype('uint8')\n    img= img*mask2[:,:,np.newaxis]\n    img[np.where((img == [0,0,0]).all(axis = 2))] = [255.0, 255.0, 255.0]\n    return img\n\ndef ext_frgd():\n    f, ax = plt.subplots(5, 5, figsize=(40,30))\n    for i in tqdm(range(25)):\n        path= os.path.join('../input/humpback-whale-identification/train', df.Image[i])\n        img_id= df.Id[i]\n        img=load(path, 300)\n        org=img.copy()\n        img= k_means(img , n_colors= 10)\n        \n        img_gray= cv2.cvtColor(np.uint8(img*255), cv2.COLOR_RGB2GRAY)\n        img_gray= cv2.medianBlur(img_gray,7)\n        edges = cv2.Canny(img_gray,100,200)\n        \n        kernel= cv2.getStructuringElement(cv2.MORPH_RECT,(15,15))\n        edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)\n        \n        top,bottom,left,right = find_box(edges)\n        rec= (left[0], top[1], right[0]-left[0], bottom[1]-top[1])\n        forground_img= forgrd_ext(org, rec)\n        \n        ax[i//5][i%5].imshow(forground_img, aspect='auto')\n        ax[i//5][i%5].set_title(img_id)\n        ax[i//5][i%5].set_xticks([]); ax[i//5][i%5].set_yticks([])\n    plt.show()\n    \n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ext_frgd()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path= os.path.join('../input/humpback-whale-identification/train', df.Image[7])\nim1= load(path, 300)\n\nim2= img= k_means(im1 , n_colors= 3)\n\nim3= cv2.cvtColor(np.uint8(im2*255), cv2.COLOR_RGB2GRAY)\nim3= cv2.medianBlur(im3,5)\nim3 = cv2.Canny(im3,100,200)\nkernel= cv2.getStructuringElement(cv2.MORPH_RECT,(15,15))\nim31 = cv2.morphologyEx(im3, cv2.MORPH_CLOSE, kernel)\n\ntop,bottom,left,right = find_box(im31)\nim4=cv2.rectangle(im1.copy(), (left[0], top[1]), (right[0], bottom[1]), (0, 255, 0), thickness=3)\n\nrec= (left[0], top[1], right[0]-left[0], bottom[1]-top[1])\nim5= forgrd_ext(im1, rec)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"![](https://i.gifer.com/7ImI.gif)\n\n## *UPVOTE* ,if you find kernel usefull :-)","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}