{"cells":[{"metadata":{},"cell_type":"markdown","source":"### I try CLAHE and Equalize using opencv2\nhttp://amroamroamro.github.io/mexopencv/opencv/clahe_demo_gui.html"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":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 in \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_path = '/kaggle/input/understanding_cloud_organization'\ntrain_csv_path = os.path.join('/kaggle/input/understanding_cloud_organization','train.csv')\ntrain_image_path = os.path.join('/kaggle/input/understanding_cloud_organization','train_images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# load full data and label no mask as -1\ntrain_df = pd.read_csv(train_csv_path).fillna(-1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# image id and class id are two seperate entities and it makes it easier to split them up in two columns\ntrain_df['ImageId'] = train_df['Image_Label'].apply(lambda x: x.split('_')[0])\ntrain_df['Label'] = train_df['Image_Label'].apply(lambda x: x.split('_')[1])\n# lets create a dict with class id and encoded pixels and group all the defaults per image\ntrain_df['Label_EncodedPixels'] = train_df.apply(lambda row: (row['Label'], row['EncodedPixels']), axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def rle_to_mask(rle_string, height, width):\n    '''\n    convert RLE(run length encoding) string to numpy array\n\n    Parameters: \n    rle_string (str): string of rle encoded mask\n    height (int): height of the mask\n    width (int): width of the mask \n\n    Returns: \n    numpy.array: numpy array of the mask\n    '''\n    \n    rows, cols = height, width\n    \n    if rle_string == -1:\n        return np.zeros((height, width))\n    else:\n        rle_numbers = [int(num_string) for num_string in rle_string.split(' ')]\n        rle_pairs = np.array(rle_numbers).reshape(-1,2)\n        img = np.zeros(rows*cols, dtype=np.uint8)\n        for index, length in rle_pairs:\n            index -= 1\n            img[index:index+length] = 255\n        img = img.reshape(cols,rows)\n        img = img.T\n        return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def graph(id_name):\n    img = cv2.imread(os.path.join(train_image_path, train_df[train_df['Image_Label']==id_name]['ImageId'].values[0]))\n    #CLAHE(OpenCV)\n    img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)\n    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))\n    img_yuv[:,:,0] = clahe.apply(img_yuv[:,:,0])\n    img1 = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)\n    #Equalize(OpenCV)\n    img_yuv1 = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)\n    img_yuv1[:,:,0] = cv2.equalizeHist(img_yuv1[:,:,0])\n    img2 = cv2.cvtColor(img_yuv1, cv2.COLOR_YUV2BGR)\n\n    mask_decoded = rle_to_mask(train_df[train_df['Image_Label']==id_name]['Label_EncodedPixels'].values[0][1], img.shape[0], img.shape[1])\n    fig, ax = plt.subplots(nrows=1, ncols=4, sharey=True, figsize=(20,10))\n    ax[0].set_title(\"{}\".format(train_df[train_df['Image_Label']==id_name]['Label'].values[0]), size = 12, color = \"blue\")\n    ax[0].imshow(img);\n    ax[1].set_title(\"CLAHE(OpenCV)\", size = 12, color = \"red\")\n    ax[1].imshow(img1);\n    ax[2].set_title(\"Equalize(OpenCV)\", size = 12, color = \"red\")\n    ax[2].imshow(img2);\n    ax[3].set_title(\"mask-image\", size = 12, color = \"red\")\n    ax[3].imshow(mask_decoded);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for name in train_df[(train_df['EncodedPixels']!=-1)&(train_df['Label']=='Fish')]['Image_Label'].tolist()[:10]:\n    graph(name)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for name in train_df[(train_df['EncodedPixels']!=-1)&(train_df['Label']=='Flower')]['Image_Label'].tolist()[:10]:\n    graph(name)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for name in train_df[(train_df['EncodedPixels']!=-1)&(train_df['Label']=='Gravel')]['Image_Label'].tolist()[:10]:\n    graph(name)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for name in train_df[(train_df['EncodedPixels']!=-1)&(train_df['Label']=='Sugar')]['Image_Label'].tolist()[:10]:\n    graph(name)","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":1}