{"cells":[{"metadata":{},"cell_type":"markdown","source":"<h2> WARNING! Experimentaion kernel , proceed at your own risk!! :D\n<h2> Hello This is just an Experimental kernel I tried as I am still learning and exploring image processing and all</h2>\n<h2>If you like it Please do Upvote :D</h2>","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"\nimport numpy as np \nimport pandas as pd \n\nimport os\ntotal_files=[]\n\nfp=\"/kaggle/input/global-wheat-detection/train/\"\nfor dirname, _, filenames in os.walk(fp):\n    total_files=filenames\n        \n\n\n\n# You can write up to 5GB 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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_df=pd.read_csv(\"/kaggle/input/global-wheat-detection/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h2> Here I try to sharpen the image by varaying the skimage's unsharp_mask amount variable </h2>","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from skimage import data\nimport numpy as np\nimport skimage.filters as filters\nimport matplotlib.pyplot as plt\nfrom skimage import io\nfig,ax=plt.subplots(1,5,figsize=(24,24))\nfor en,i in enumerate([1.5,2,2.5,3,3.5]):    \n    image = io.imread('/kaggle/input/global-wheat-detection/train/'+str(train_df.loc[0,\"image_id\"])+\".jpg\")\n    if en==0:\n        ax[en].imshow(image)\n    \n        continue\n    \n    gimage=filters.unsharp_mask(image,amount=i)\n    ax[en].imshow(gimage)\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":" <h3>Whats image processing without histograms man? well I drew one just to show the peak values :D","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\nimport skimage.segmentation as seg\nimport skimage.filters as filters\nimport skimage.draw as draw\nimport skimage.color as color\nimport skimage.transform as tfm\n\ndef image_show(image, nrows=1, ncols=1,cmap=\"gray\"):\n    fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(8, 8))\n    ax.imshow(image,cmap=\"gray\")\n    ax.axis('off')\n    return fig, ax\nfig,ax=plt.subplots(1,1)\nax.hist(image.ravel(),bins=64,range=[0,256])\nax.set_xlim(0,256)\n#image_show(image>20)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h3> Now I use the peak values from the above histogram to try and extract the Corn Heads\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfig,ax=plt.subplots(1,5,figsize=(12,12))\nfor en,i in enumerate([0,50,60,80,100]):\n            \n    image = io.imread('/kaggle/input/global-wheat-detection/train/'+str(train_df.loc[0,\"image_id\"])+\".jpg\")\n    if en==0:\n        \n        ax[en].imshow(tfm.resize(image,(512,512)))\n        continue\n   \n    mask=image<i\n    image[mask]=0\n    \n    gimage=color.rgb2gray(image)\n    ax[en].imshow(filters.unsharp_mask(gimage,radius=0.05),cmap=\"gray\")\n#image_show(fimage)\n\n#segmented\n#image.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h3> NOW SOME SEGMENTATION ALGOS :D\n<h4> The various segmentation algorithms I have applied are as follows\n    <ul>Here I use the following algos\n    <li>Li’s iterative Minimum Cross Entropy</li>\n    <li>  triangle algorithm.</li>\n       <li>   Yen’s method.</li>\n           <li>  ISODATA method,</li>\n           <li>  Sauvola local threshold </li>","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"t_filter=[filters.threshold_li,\nfilters.threshold_triangle,\n          filters.threshold_yen,\n          filters.threshold_isodata,\n          filters.threshold_sauvola\n         ]\nfig,ax=plt.subplots(1,5,figsize=(32,32))\nfig.tight_layout(pad=3.0)\nfor en,i in enumerate(t_filter):\n    tit=str(i)       \n    image = io.imread('/kaggle/input/global-wheat-detection/train/'+str(train_df.loc[0,\"image_id\"])+\".jpg\")\n   \n    i=i(image)\n    mask=image<i\n    image[mask]=0\n    \n    gimage=(color.rgb2gray(filters.unsharp_mask(image,amount=3)))\n    ax[en].imshow(gimage,cmap=\"gray\")\n    ax[en].set_title(tit,fontsize=20)\n#image_show(fimage)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"<h4> SOME MORE SEGMENTAION ALGOS!!","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"t_filter=[\nfilters.threshold_mean,\n          filters.threshold_minimum,\n          filters.threshold_niblack,\n          filters.threshold_yen\n         ]\n\nfig,ax=plt.subplots(1,4,figsize=(22,22))\nfig.tight_layout(pad=3.0)\nfor en,i in enumerate(t_filter):\n    tit=str(i)       \n    image = io.imread('/kaggle/input/global-wheat-detection/train/'+str(train_df.loc[0,\"image_id\"])+\".jpg\")\n   \n    \n    i=i(image)\n    mask=image<i\n    image[mask]=0\n    \n    gimage=(color.rgb2gray(filters.unsharp_mask(image,amount=3)))\n    ax[en].imshow(gimage,cmap=\"gray\")\n    ax[en].set_title(tit)\n#image_show(fimage)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h4> Here I use the threshold_yen inorder to segment out the labels , I made a function of it so it can also store the boundingboxes which we can use to store it in the dataframe :D","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\nfrom skimage import data\nfrom skimage.filters import threshold_yen\nfrom skimage.segmentation import clear_border\nfrom skimage.measure import label, regionprops\nfrom skimage.morphology import closing, square,rectangle,convex_hull_object\nfrom skimage.color import label2rgb\n\ndef make_rect(name):\n    \n    n_image = io.imread('/kaggle/input/global-wheat-detection/test/'+str(name))\n\n    image = color.rgb2gray(n_image)\n\n\n    thresh = filters.threshold_yen(image)\n    \n    bw=closing(image < thresh, square(4))\n    \n    #bw = convex_hull_object(bw)\n    \n\n    \n    label_image = label(bw,connectivity=1,background=255)\n\n    image_label_overlay = label2rgb(label_image, image=image, bg_label=0)\n\n    \n\n\n    fig, ax = plt.subplots(figsize=(10, 6))\n    regionprops(label_image)\n    ax.imshow(n_image)\n\n    listrect=[]\n    for region in regionprops(label_image):\n        # take regions with large enough areas\n        if region.area >= 500:\n            # draw rectangle around segmented coins\n            minr, minc, maxr, maxc = region.bbox\n            listrect.append([minc,minr,maxc-minc,maxr-minr])\n            \n            rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,\n                                      fill=False, edgecolor='red', linewidth=2)\n            ax.add_patch(rect)\n\n    \n    return listrect\n    \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"d=dict()\nfp=\"/kaggle/input/global-wheat-detection/test/\"\nfor dirname, _, filenames in os.walk(fp):\n    total_files=filenames\ndata_list=list(set(train_df[\"image_id\"].values))\nfor k in range(len(data_list)):\n    data_list[k]=data_list[k]+\".jpg\"\nnotthere=[]\nfor i in filenames:\n    if i not in data_list:\n        notthere.append(i)\nprint(len(notthere))\n    \n\n#for i in filenames","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"<h3> Here i try to find the bounding boxes from the grayscale and thresholded images \n<h3> the output is not good as it considers many of the connected black areas of the images as objects too so I still need to improve on it any suggestions welcome :D\n\n\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"temp_df=pd.DataFrame({\"image_id\":[],\"width\":[],\"height\":[],\"bbox\":[],\"source\":[]})\n\nfor i in notthere:\n    rects=make_rect(i)\n    rects=rects\n    #print(rects)\n    rects=\" \".join(str(item) for innerlist in rects for item in innerlist)\n    #print(rects)\n    d={\"image_id\":[],\"width\":[],\"height\":[],\"bbox\":[],\"source\":[]}\n    #print(rects)\n    \n    \n    d[\"bbox\"].append(rects)\n    d[\"image_id\"].append(i[:-4])\n    d[\"width\"].append(1024)\n    d[\"height\"].append(1024)\n    d[\"source\"].append(\"MyOwnWhoCaresGonnaDropItAnyWay\")\n       # print(pd.DataFrame(d))  \n    temp_df=temp_df.append(pd.DataFrame(d),ignore_index=True)\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#temp_df[\"image_id\"]=temp_df[\"image_id\"].apply(lambda x: x[:-4])\ntemp_df[\"bbox\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fp='/kaggle/input/global-wheat-detection/sample_submission.csv'\ndf=pd.read_csv(fp)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df[\"PredictionString\"]=temp_df[\"bbox\"]\n\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.to_csv(\"submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"  <h2> Thank you for viewing my kernel and sorry if you did not get what you were looking for as this is just an experimentation kernel for my learning also :D","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":{"trusted":true},"cell_type":"code","source":"","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}