{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"pip install mahotas","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[24]:\n\n\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport numpy as np\nget_ipython().run_line_magic('matplotlib', 'notebook')\nfrom sklearn import svm, metrics, datasets\nfrom sklearn.utils import Bunch\nfrom sklearn.model_selection import GridSearchCV, train_test_split\nimport skimage \nfrom skimage import io \nfrom skimage.transform import resize\nfrom PIL import Image\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import MinMaxScaler\nimport os\n#imported mahotas library for haralick feature descriptor\nimport mahotas\n#imported opencv cv2 for color histogram and humoments\nimport cv2\n#from sklearn import svm\n#from sklearn import metrics\nfrom sklearn.metrics import accuracy_score\n\n\n# In[25]:\n\n\n# declaring a class for collecting the data information and data path is set \nclass Configuration:\n    def __init__(self):\n        self.maxwidth =0\n        self.maxheight=0\n        self.minwidth = 35000\n        self.minheight = 35000\n        self.imgcount=0\n        self.img_width_adjust = 480\n        self.img_height_adjust= 360\n        self.data_dir = \"../input/imgs/train\"\n\n\n# In[26]:\n\n\n#creating an config object \nconfig = Configuration()\n\n\n# In[27]:\n\n\n#function for finding the max,min  heights and max,min widths. It traverses throught the all folders and count\n#number of images in the entire data. Update the respective values in the config object accordingly. \ndef calculateDimension(path):\n    for subdir, dirs, files in os.walk(path):\n        for file in files:\n            if file.endswith(\".jpg\"):\n                config.imgcount+=1\n                filename = os.path.join(subdir, file)\n                image = io.imread(filename)\n                width = image.shape[0]\n                height = image.shape[1]\n                if width < config.minwidth:\n                    config.minwidth = width\n                if height < config.minheight:\n                    config.minheight = height\n                if width > config.maxwidth:\n                    config.maxwidth = width\n                if height > config.maxheight:\n                    config.maxheight = height\n    return\n\n\n# In[28]:\n\n\ncalculateDimension(config.data_dir)\nprint(\"Minimum Width:\\t\",config.minwidth)\nprint(\"Minimum Height:\\t\",config.minheight)\nprint(\"Maximum Width:\\t\",config.maxwidth)\nprint(\"Maximum Height:\\t\",config.maxheight)\nprint(\"Image Count:\\t\",config.imgcount)\n\n\n# In[29]:\n\n\nfixed_size = tuple((64, 64))\n\n\n# In[30]:\n\n\n#used global feature descriptors HuMoments functions for gathering the shape details\ndef fd_hu_moments(image):\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    # extract the shape feature vector\n    feature = cv2.HuMoments(cv2.moments(image)).flatten()\n    return feature\n\n\n# In[31]:\n\n\n#used global feature descriptors haralick functions for gatahering the texture details\ndef fd_haralick(image):\n    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    # extract texture feature vector. This function expects the image to be in gray scale\n    haralick = mahotas.features.haralick(gray).mean(axis=0)\n    return haralick\n\n\n# In[32]:\n\n\n#used global feature descriptors colorhistogram functions for gathering the color details\nbins = 8\ndef fd_histogram(image, mask=None):\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n    #extract color feature vector\n    hist  = cv2.calcHist([image], [0, 1, 2], None, [bins, bins, bins], [0, 256, 0, 256, 0, 256])\n    cv2.normalize(hist, hist)\n    return hist.flatten()\n\n\n# In[33]:\n\n\ndef load_image_files(container_path,dimension=(64, 64)):\n    image_dir = Path(container_path)\n    folders = [directory for directory in image_dir.iterdir() if directory.is_dir()]\n    categories = [fo.name for fo in folders]\n    \n    print(categories)\n    print(folders)\n    print(image_dir)\n    \n    images = []\n    flat_data = []\n    target = []\n    global_features = []\n    for i, direc in enumerate(folders):\n        # get the current training label\n        current_label = direc.name\n        for file in direc.iterdir():\n            file = str(file)\n            image = cv2.imread(file)\n            #resizing the image to 64*64\n            image = cv2.resize(image, dimension)\n            target.append(current_label)\n            # Global feature extraction is done here \n            fv_hu_moments = fd_hu_moments(image)\n            fv_haralick   = fd_haralick(image)\n            fv_histogram  = fd_histogram(image)\n            #combing the global feautures  \n            global_feature = np.hstack([fv_histogram, fv_haralick, fv_hu_moments])\n            global_features.append(global_feature)\n        print(current_label)\n        print(\"feature extraction done with folder: {}\".format(current_label))\n\n    print(\"Entire Feature Extraction done\")\n    return global_features,target\n\n\n# In[34]:\n\n\nglobal_features,labels = load_image_files(\"../input/state-farm-distracted-driver-detection/imgs/train\")\n\n\n# In[35]:\n\n\n#encoding the target labels \ntargetNames = np.unique(labels)\nle = LabelEncoder()\ntarget = le.fit_transform(labels)\nprint(\"training labels encoded\")\nprint(target)\n\n\n# In[36]:\n\n\nprint(global_features[0].shape)\n\n\n# In[37]:\n\n\n# normalize the feature vector in the range (0-1)\nscaler = MinMaxScaler(feature_range=(0, 1))\nrescaled_features = scaler.fit_transform(global_features)\nprint(\"feature vector normalized\")\n\nprint(\"target labels: {}\".format(target))\nprint(\"target labels shape: {}\".format(target.shape))\n\n# get the overall feature vector size\nprint(\"feature vector size {}\".format(np.array(global_features).shape))\n\n\n# In[38]:\n\n\nglobal_features = np.array(rescaled_features)\nglobal_labels = np.array(target)\n\n\n# In[39]:\n\n\n(trainDataGlobal, testDataGlobal, trainLabelsGlobal, testLabelsGlobal) = train_test_split(global_features,global_labels,\n                                                                test_size=0.30,random_state=9)\n\n\n# In[40]:\n\n\nprint(\"Train data  : {}\".format(trainDataGlobal.shape))\nprint(\"Test data   : {}\".format(testDataGlobal.shape))\nprint(\"Train labels: {}\".format(trainLabelsGlobal.shape))\nprint(\"Test labels : {}\".format(testLabelsGlobal.shape))\n\n\n# In[41]:\n\n\nclf = svm.SVC(C=5, gamma=10,kernel='rbf')\nclf.fit(trainDataGlobal, trainLabelsGlobal)\n\n\n# In[42]:\n\n\ny_pred = clf.predict(testDataGlobal)\nprint(metrics.classification_report(testLabelsGlobal, y_pred))\nprint(\"Accuracy Score  : {}\".format(accuracy_score(testLabelsGlobal, y_pred)))\n\n\n# In[ ]:\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","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}