{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.0"}},"nbformat":4,"nbformat_minor":0,"cells":[{"cell_type":"markdown","metadata":{"_cell_guid":"56ef5115-1d75-3560-92f8-d6a74f2ef7d2","_active":false},"source":"It might be necessary to segment the images so as to extract some features to be used in classification.\nHere is one of the ways to segment using Guassian Mixture Models.\n\nImages are converted from RGB space to Lab color space\nSmoothing is performed on 'a'\nThen GMM is used to segment into various components.\n\nI have used Initial code from a Notebook describing how to connect to coflax.","outputs":[]},{"cell_type":"code","execution_count":2,"metadata":{"_cell_guid":"9d86e58c-4c50-84d9-08d6-cf8b26dc4130","_active":false},"outputs":[],"source":"import os\nimport platform\n\n\nabspath_dataset_dir_train_1 = '/data/kaggle/train/Type_1'\nabspath_dataset_dir_train_2 = '/data/kaggle/train/Type_2'\nabspath_dataset_dir_train_3 = '/data/kaggle/train/Type_3'\nabspath_dataset_dir_test    = '/data/kaggle/test/'\n\n# For kaggle kernels\nif 'c001' not in platform.node():\n    abspath_dataset_dir_train_1 = '../input/train/Type_1'\n    abspath_dataset_dir_train_2 = '../input/train/Type_2'\n    abspath_dataset_dir_train_3 = '../input/train/Type_3'\n    abspath_dataset_dir_test    = '../input/test/'\n\n    \ndef get_list_abspath_img(abspath_dataset_dir):\n    list_abspath_img = []\n    for str_name_file_or_dir in os.listdir(abspath_dataset_dir):\n        if ('.jpg' in str_name_file_or_dir) == True:\n            list_abspath_img.append(os.path.join(abspath_dataset_dir, str_name_file_or_dir))\n    list_abspath_img.sort()\n    return list_abspath_img\n\n\nlist_abspath_img_train_1 = get_list_abspath_img(abspath_dataset_dir_train_1)\nlist_abspath_img_train_2 = get_list_abspath_img(abspath_dataset_dir_train_2)\nlist_abspath_img_train_3 = get_list_abspath_img(abspath_dataset_dir_train_3)\nlist_abspath_img_test    = get_list_abspath_img(abspath_dataset_dir_test)\n\nlist_abspath_img_train        = list_abspath_img_train_1 + list_abspath_img_train_2 + list_abspath_img_train_3\nlist_answer_dataset_dir_train = [1] * len(list_abspath_img_train_1) + [2] * len(list_abspath_img_train_2) + [3] * len(list_abspath_img_train_3)","execution_state":"idle"},{"cell_type":"code","execution_count":3,"metadata":{"_cell_guid":"475d092a-05ef-4cff-e411-110e34b9f676","_active":false},"outputs":[],"source":"import cv2\nimport matplotlib.pyplot\nimport numpy as np\nfrom sklearn.mixture import GaussianMixture\nimport matplotlib.pyplot as plt\n\ndef sub_func_load_img(abspath_img):\n    img_rgb = cv2.cvtColor(cv2.imread(abspath_img), cv2.COLOR_BGR2RGB)\n    return cv2.resize(img_rgb,(0,0), fx=0.05, fy=0.05)\n\ndef show_img(abspath_img):\n    matplotlib.pyplot.imshow(sub_func_load_img(abspath_img))\n    matplotlib.pyplot.show()","execution_state":"idle"},{"cell_type":"code","execution_count":33,"metadata":{"_cell_guid":"8e18f220-d7b2-3fd1-8853-9c5a95894e38","_active":false,"collapsed":false},"outputs":[],"source":"rgb = sub_func_load_img(list_abspath_img_train[252])\nlab = cv2.cvtColor(rgb,cv2.COLOR_RGB2LAB)\n\nimglab = cv2.medianBlur(lab,41)\nnp.random.seed(1)\nimgdata = imglab[:,:,1]#Take 'a' component\nflatImgL = imgdata.flatten()\ng = GaussianMixture(n_components=2,covariance_type='diag')\ng.fit(flatImgL[:,np.newaxis])\nlabel_data = g.predict(flatImgL[:,np.newaxis])\nlabel_data= label_data.reshape(imgdata.shape)\n\nndx = label_data[:,:] == 1\nndx = ndx.astype(float)\n\nmask = np.zeros_like(rgb)\nfor i in np.arange(3):\n    mask[:,:,i]= ndx\n    \nplt.imshow(rgb)\nplt.show()\nsegImg = np.multiply(rgb,mask)\nplt.imshow(np.multiply(rgb,mask))\nplt.show()","execution_state":"idle"},{"cell_type":"code","execution_count":34,"metadata":{"_cell_guid":"ed9d44e7-e2e2-292b-76d1-6a02b845dead","_active":false},"outputs":[],"source":"chans = cv2.split(segImg)\ncolors = (\"r\", \"g\", \"b\")\nplt.title(\"'Flattened' Color Histogram\")\nplt.xlabel(\"Bins\")\nplt.ylabel(\"# of Pixels\")\nfeatures = []\nfor (chan, color) in zip(chans, colors):\n    hist = cv2.calcHist([chan], [0], None, [256], [2, 256])\n    features.extend(hist)\n    # plot the histogram\n    plt.plot(hist, color = color)\n    plt.xlim([0, 256])\n","execution_state":"idle"},{"metadata":{"_cell_guid":"9cab06b1-660e-c773-d258-b1b53b946e9a","_active":true,"collapsed":false},"source":"# import the necessary packages\nfrom skimage import feature\nimport numpy as np\n \nclass LocalBinaryPatterns:\n\tdef __init__(self, numPoints, radius):\n\t\t# store the number of points and radius\n\t\tself.numPoints = numPoints\n\t\tself.radius = radius\n \n\tdef describe(self, image, eps=1e-7):\n\t\t# compute the Local Binary Pattern representation\n\t\t# of the image, and then use the LBP representation\n\t\t# to build the histogram of patterns\n\t\tlbp = feature.local_binary_pattern(image, self.numPoints,\n\t\t\tself.radius, method=\"uniform\")\n\t\t(hist, _) = np.histogram(lbp.ravel(),\n\t\t\tbins=np.arange(0, 149))\n\t\t\t\n \n\t\t# normalize the histogram\n\t\thist = hist.astype(\"float\")\n\t\thist /= (hist.sum() + eps)\n \n\t\t# return the histogram of Local Binary Patterns\n\t\treturn hist\n# initialize the local binary patterns descriptor along with\n# the data and label lists\n\ndesc = LocalBinaryPatterns(24,3)\nplt.title(\"Histogram of LBP\")\nplt.xlabel(\"Bins\")\nplt.ylabel(\"# of Pixels\")\nfeatures = []\nfor (chan, color) in zip(chans, colors):\n    hist = desc.describe(chan)\n    # plot the histogram\n    plt.plot(hist, color = color)\n    plt.xlim([0, 30])\n\n","execution_count":35,"cell_type":"code","outputs":[],"execution_state":"idle"}]}