{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.10","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":31703,"databundleVersionId":2871752,"sourceType":"competition"},{"sourceId":3161996,"sourceType":"datasetVersion","datasetId":1739948},{"sourceId":7919938,"sourceType":"datasetVersion","datasetId":4653984}],"dockerImageVersionId":30145,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"pip install ffmpeg","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:22:35.590856Z","iopub.execute_input":"2024-03-23T06:22:35.591437Z","iopub.status.idle":"2024-03-23T06:22:51.337484Z","shell.execute_reply.started":"2024-03-23T06:22:35.591293Z","shell.execute_reply":"2024-03-23T06:22:51.336265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings('ignore')\nimport cv2\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport random\nimport ffmpeg\nfrom IPython.display import Video\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport logging\nfrom itertools import cycle\n\nlogging.disable(logging.WARNING)\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\n\nplt.style.use('ggplot')\ncm = sns.light_palette(\"green\", as_cmap=True)\npd.option_context('display.max_colwidth', 100)\ncolor_pal = plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"]\ncolor_cycle = cycle(plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"])","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:32:42.172639Z","iopub.execute_input":"2024-03-23T06:32:42.173109Z","iopub.status.idle":"2024-03-23T06:32:51.144282Z","shell.execute_reply.started":"2024-03-23T06:32:42.173069Z","shell.execute_reply":"2024-03-23T06:32:51.143233Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# SEED EVERYTHING\nrandom.seed(hash(\"setting random seeds\") % 2**32 - 1)\nnp.random.seed(hash(\"improves reproducibility\") % 2**32 - 1)\n\n# config\nclass config:\n    BASE_DIR = \"../input/tensorflow-great-barrier-reef/train_images/\"","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:32:57.895472Z","iopub.execute_input":"2024-03-23T06:32:57.895819Z","iopub.status.idle":"2024-03-23T06:32:57.902141Z","shell.execute_reply.started":"2024-03-23T06:32:57.895774Z","shell.execute_reply":"2024-03-23T06:32:57.901086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training of Data\n","metadata":{}},{"cell_type":"code","source":"img_og = plt.imread('../input/tensorflow-great-barrier-reef/train_images/video_1/9101.jpg')\nimg_9101 = cv2.imread('../input/tensorflow-great-barrier-reef/train_images/video_1/9101.jpg')","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:33:02.429931Z","iopub.execute_input":"2024-03-23T06:33:02.430440Z","iopub.status.idle":"2024-03-23T06:33:02.568818Z","shell.execute_reply.started":"2024-03-23T06:33:02.430400Z","shell.execute_reply":"2024-03-23T06:33:02.567729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('../input/tensorflow-great-barrier-reef/train.csv')\ntrain_dir = \"../input/tensorflow-great-barrier-reef/train_images\"\ndf['image_path'] = train_dir + \"/video_\" + df['video_id'].astype(str) + \"/\" + df['video_frame'].astype(str) + \".jpg\"\ndf.head().style.set_properties(**{'background-color': 'black',\n                           'color': 'lawngreen',\n                           'border-color': 'white'})","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:33:04.102012Z","iopub.execute_input":"2024-03-23T06:33:04.103494Z","iopub.status.idle":"2024-03-23T06:33:04.357906Z","shell.execute_reply.started":"2024-03-23T06:33:04.103446Z","shell.execute_reply":"2024-03-23T06:33:04.356897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.info() # lets check more details about the data","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:33:16.448205Z","iopub.execute_input":"2024-03-23T06:33:16.448536Z","iopub.status.idle":"2024-03-23T06:33:16.476833Z","shell.execute_reply.started":"2024-03-23T06:33:16.448501Z","shell.execute_reply":"2024-03-23T06:33:16.475553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df[df.annotations.str.len() > 2].head(5).style.background_gradient(cmap=cm) # filling up the annotation column","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:33:06.000112Z","iopub.execute_input":"2024-03-23T06:33:06.000678Z","iopub.status.idle":"2024-03-23T06:33:06.052590Z","shell.execute_reply.started":"2024-03-23T06:33:06.000620Z","shell.execute_reply":"2024-03-23T06:33:06.051358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['annotations'] = df['annotations'].apply(eval)\ndf_train_v2 = df[df.annotations.str.len() > 0 ].reset_index(drop=True)\ndf_train_v2.head(5).style.background_gradient(cmap='Reds')","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:33:23.742458Z","iopub.execute_input":"2024-03-23T06:33:23.742754Z","iopub.status.idle":"2024-03-23T06:33:24.245142Z","shell.execute_reply.started":"2024-03-23T06:33:23.742722Z","shell.execute_reply":"2024-03-23T06:33:24.244099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# https://www.kaggle.com/julian3833/reef-a-cv-strategy-subsequences\ndf = pd.read_csv(\"/kaggle/input/tensorflow-great-barrier-reef/train.csv\")\ndf['annotations'] = df['annotations'].apply(eval)\ndf['n_annotations'] = df['annotations'].str.len()\ndf['has_annotations'] = df['annotations'].str.len() > 0\ndf['has_2_or_more_annotations'] = df['annotations'].str.len() >= 2\ndf['doesnt_have_annotations'] = df['annotations'].str.len() == 0\ndf['image_path'] = config.BASE_DIR + \"video_\" + df['video_id'].astype(str) + \"/\" + df['video_frame'].astype(str) + \".jpg\"","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:33:25.806061Z","iopub.execute_input":"2024-03-23T06:33:25.807121Z","iopub.status.idle":"2024-03-23T06:33:26.279630Z","shell.execute_reply.started":"2024-03-23T06:33:25.807071Z","shell.execute_reply":"2024-03-23T06:33:26.278518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_agg = df.groupby([\"video_id\", 'sequence']).agg({'sequence_frame': 'count', 'has_annotations': 'sum', 'doesnt_have_annotations': 'sum'})\\\n           .rename(columns={'sequence_frame': 'Total Frames', 'has_annotations': 'Frames with at least 1 object', 'doesnt_have_annotations': \"Frames with no object\"})\ndf_agg","metadata":{"execution":{"iopub.status.busy":"2024-03-22T13:30:15.568580Z","iopub.execute_input":"2024-03-22T13:30:15.569388Z","iopub.status.idle":"2024-03-22T13:30:15.596278Z","shell.execute_reply.started":"2024-03-22T13:30:15.569326Z","shell.execute_reply":"2024-03-22T13:30:15.595602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Preparation:","metadata":{}},{"cell_type":"markdown","source":"### Lets check we have images with same size or not:","metadata":{}},{"cell_type":"code","source":"img_sizes = []\nfor i in df_train_v2[\"image_path\"]:\n    img_sizes.append(plt.imread(i).shape)\n\nnp.unique(img_sizes)","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:33:29.493722Z","iopub.execute_input":"2024-03-23T06:33:29.494081Z","iopub.status.idle":"2024-03-23T06:36:58.990494Z","shell.execute_reply.started":"2024-03-23T06:33:29.494045Z","shell.execute_reply":"2024-03-23T06:36:58.989266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# lets check total number of images with annotations\nlen(df_train_v2)","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:37:31.073530Z","iopub.execute_input":"2024-03-23T06:37:31.073960Z","iopub.status.idle":"2024-03-23T06:37:31.081154Z","shell.execute_reply.started":"2024-03-23T06:37:31.073922Z","shell.execute_reply":"2024-03-23T06:37:31.080286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Underwater Image Enhancement","metadata":{}},{"cell_type":"code","source":"def he_hsv(img_demo):\n    img_hsv = cv2.cvtColor(img_demo, cv2.COLOR_RGB2HSV)\n\n    # Histogram equalisation on the V-channel\n    img_hsv[:, :, 2] = cv2.equalizeHist(img_hsv[:, :, 2])\n\n    # convert image back from HSV to RGB\n    image_hsv = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2RGB)\n    \n    return image_hsv","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:37:34.998476Z","iopub.execute_input":"2024-03-23T06:37:34.998904Z","iopub.status.idle":"2024-03-23T06:37:35.010267Z","shell.execute_reply.started":"2024-03-23T06:37:34.998862Z","shell.execute_reply":"2024-03-23T06:37:35.008752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_img(img_dir,num_items,func,mode):\n    img_list = random.sample(os.listdir(img_dir), num_items)\n\n    for i in range(len(img_list)):\n        full_path = img_dir + '/' + img_list[i]\n        img_temp1 = plt.imread(full_path)\n        img_temp_cv = cv2.imread(full_path)\n        plt.figure(figsize=(20,15))\n        plt.subplot(1,2,1)\n        plt.imshow(img_temp1);\n        plt.subplot(1,2,2)\n        if mode == 'plt':\n            plt.imshow(func(img_temp1));\n        elif mode == 'cv2':\n            plt.imshow(func(img_temp_cv));\n            ","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:41:07.902381Z","iopub.execute_input":"2024-03-23T06:41:07.902792Z","iopub.status.idle":"2024-03-23T06:41:07.912464Z","shell.execute_reply.started":"2024-03-23T06:41:07.902754Z","shell.execute_reply":"2024-03-23T06:41:07.911510Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vid_0_dir = \"../input/tensorflow-great-barrier-reef/train_images/video_0\"\nnum_items1 = 4\nplot_img(vid_0_dir,num_items1,he_hsv,\"plt\")","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:41:20.750011Z","iopub.execute_input":"2024-03-23T06:41:20.751014Z","iopub.status.idle":"2024-03-23T06:41:25.449461Z","shell.execute_reply.started":"2024-03-23T06:41:20.750961Z","shell.execute_reply":"2024-03-23T06:41:25.448224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport cv2\nimport matplotlib.pyplot as plt\n\ndef plot_img(directory, num_items, plot_func, plot_type):\n   \n    Plot images from a directory using the given plotting function.\n    \n    fig = plt.figure(figsize=(15, 10))  # Adjust the figure size as needed\n    \n    # Get list of image filenames in the directory\n    image_files = os.listdir(directory)[:num_items]\n    \n    for i, image_file in enumerate(image_files, 1):\n        image_path = os.path.join(directory, image_file)\n        \n        # Read the image\n        image = cv2.imread(image_path)\n        \n        # Plot the image\n        plt.subplot(1, num_items, i)\n        plot_func(image)\n        plt.axis('off')  # Turn off axes\n        plt.title(image_file)  # Add title with image filename\n    \n    plt.tight_layout()  # Adjust layout to avoid overlap of titles\n    plt.show()\n\n\ndef plot_cv2_img(image):\n   \n    # Convert BGR to RGB\n    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    \n    # Display the image\n    plt.imshow(image_rgb)\n\n# Example usage:\nvid_0_dir = \"../input/tensorflow-great-barrier-reef/train_images/video_0\"\nnum_items1 = 4\nplot_img(vid_0_dir, num_items1, plot_cv2_img, \"plt\")\n","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:44:54.643614Z","iopub.execute_input":"2024-03-23T06:44:54.644019Z","iopub.status.idle":"2024-03-23T06:44:55.521203Z","shell.execute_reply.started":"2024-03-23T06:44:54.643979Z","shell.execute_reply":"2024-03-23T06:44:55.520458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def RecoverHE(sceneRadiance):\n    for i in range(3):\n        sceneRadiance[:, :, i] =  cv2.equalizeHist(sceneRadiance[:, :, i])\n    return sceneRadiance\n\nvid_0_dir = \"../input/tensorflow-great-barrier-reef/train_images/video_0\"\nnum_items1 = 4\nplot_img(vid_0_dir,num_items1,RecoverHE,\"cv2\")","metadata":{"execution":{"iopub.status.busy":"2024-02-25T14:18:32.237562Z","iopub.execute_input":"2024-02-25T14:18:32.238722Z","iopub.status.idle":"2024-02-25T14:18:36.274379Z","shell.execute_reply.started":"2024-02-25T14:18:32.238662Z","shell.execute_reply":"2024-02-25T14:18:36.273612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport cv2\nimport matplotlib.pyplot as plt\n\ndef plot_img(directory, num_items, process_func, plot_type):\n  \n    fig = plt.figure(figsize=(15, 10))  # Adjust the figure size as needed\n    \n    # Get list of image filenames in the directory\n    image_files = os.listdir(directory)[:num_items]\n    \n    for i, image_file in enumerate(image_files, 1):\n        image_path = os.path.join(directory, image_file)\n        \n        # Read the image\n        image = cv2.imread(image_path)\n        \n        # Process the image using the provided function\n        processed_image = process_func(image)\n        \n        # Plot the image\n        plt.subplot(1, num_items, i)\n        plot_cv2_img(processed_image)\n        plt.axis('off')  # Turn off axes\n        plt.title(image_file)  # Add title with image filename\n    \n    plt.tight_layout()  # Adjust layout to avoid overlap of titles\n    plt.show()\n\n# Define a plotting function for OpenCV images\ndef plot_cv2_img(image):\n\n    # Convert BGR to RGB\n    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    \n    # Display the image\n    plt.imshow(image_rgb)\n\n# Define the RecoverHE function\ndef RecoverHE(sceneRadiance):\n   \n    for i in range(3):\n        sceneRadiance[:, :, i] = cv2.equalizeHist(sceneRadiance[:, :, i])\n    return sceneRadiance\n\n# Example usage:\nvid_0_dir = \"../input/tensorflow-great-barrier-reef/train_images/video_0\"\nnum_items1 = 4\nplot_img(vid_0_dir, num_items1, RecoverHE, \"cv2\")\n","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:46:14.074069Z","iopub.execute_input":"2024-03-23T06:46:14.076479Z","iopub.status.idle":"2024-03-23T06:46:14.887162Z","shell.execute_reply.started":"2024-03-23T06:46:14.076409Z","shell.execute_reply":"2024-03-23T06:46:14.884772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def RecoverCLAHE(sceneRadiance):\n    clahe = cv2.createCLAHE(clipLimit=7, tileGridSize=(14, 14))\n    for i in range(3):\n\n        \n        sceneRadiance[:, :, i] = clahe.apply((sceneRadiance[:, :, i]))\n\n\n    return sceneRadiance\n\nvid_0_dir = \"../input/tensorflow-great-barrier-reef/train_images/video_0\"\nnum_items1 = 4\nplot_img(vid_0_dir,num_items1,RecoverCLAHE,\"cv2\")","metadata":{"execution":{"iopub.status.busy":"2024-02-27T04:19:30.546600Z","iopub.execute_input":"2024-02-27T04:19:30.546979Z","iopub.status.idle":"2024-02-27T04:19:35.609686Z","shell.execute_reply.started":"2024-02-27T04:19:30.546941Z","shell.execute_reply":"2024-02-27T04:19:35.608768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def clahe_hsv(img):\n    hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n    h, s, v = hsv_img[:,:,0], hsv_img[:,:,1], hsv_img[:,:,2]\n    clahe = cv2.createCLAHE(clipLimit = 15.0, tileGridSize = (20,20))\n    v = clahe.apply(v)\n\n    hsv_img = np.dstack((h,s,v))\n\n    rgb = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2RGB)\n    \n    return rgb\n\n\nvid_0_dir = \"../input/tensorflow-great-barrier-reef/train_images/video_0\"\nnum_items1 = 4\nplot_img(vid_0_dir,num_items1,clahe_hsv,\"cv2\")","metadata":{"execution":{"iopub.status.busy":"2024-02-27T04:18:49.989466Z","iopub.execute_input":"2024-02-27T04:18:49.989876Z","iopub.status.idle":"2024-02-27T04:18:54.480285Z","shell.execute_reply.started":"2024-02-27T04:18:49.989831Z","shell.execute_reply":"2024-02-27T04:18:54.478975Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#  Enhancemnt using Gamma Correction:","metadata":{}},{"cell_type":"code","source":"def gamma_enhancement(image,gamma):\n    R = 255.0\n    return (R * np.power(image.astype(np.uint32)/R, gamma)).astype(np.uint8)\n\nplt.figure(figsize=(20,15))\nplt.subplot(2,2,1)\nplt.imshow(img_og);\nplt.subplot(2,2,2)\nplt.imshow(gamma_enhancement(img_9101,1/0.6))\n\nplt.subplot(2,2,3)\nplt.imshow(img_og);\nplt.subplot(2,2,4)\nplt.imshow(gamma_enhancement(img_og,1/0.6))\n","metadata":{"execution":{"iopub.status.busy":"2024-02-27T04:20:00.957350Z","iopub.execute_input":"2024-02-27T04:20:00.958520Z","iopub.status.idle":"2024-02-27T04:20:03.521991Z","shell.execute_reply.started":"2024-02-27T04:20:00.958459Z","shell.execute_reply":"2024-02-27T04:20:03.509965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Enhancement using Scene Radiance\n","metadata":{}},{"cell_type":"code","source":"def RecoverGC(sceneRadiance):\n    sceneRadiance = sceneRadiance/255.0\n    \n    for i in range(3):\n        sceneRadiance[:, :, i] =  np.power(sceneRadiance[:, :, i] / float(np.max(sceneRadiance[:, :, i])), 3.2)\n    sceneRadiance = np.clip(sceneRadiance*255, 0, 255)\n    sceneRadiance = np.uint8(sceneRadiance)\n    return sceneRadiance\n\nvid_0_dir = \"../input/tensorflow-great-barrier-reef/train_images/video_0\"\nnum_items1 = 4\nplot_img(vid_0_dir,num_items1,RecoverGC,\"cv2\")","metadata":{"execution":{"iopub.status.busy":"2024-02-27T04:20:13.183040Z","iopub.execute_input":"2024-02-27T04:20:13.183465Z","iopub.status.idle":"2024-02-27T04:20:18.831174Z","shell.execute_reply.started":"2024-02-27T04:20:13.183419Z","shell.execute_reply":"2024-02-27T04:20:18.829469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef plot_img(directory, num_items, plot_func, plot_type):\n  \n    fig = plt.figure(figsize=(15, 10))  # Adjust the figure size as needed\n    \n    # Get list of image filenames in the directory\n    image_files = os.listdir(directory)[:num_items]\n    \n    for i, image_file in enumerate(image_files, 1):\n        image_path = os.path.join(directory, image_file)\n        \n        # Read the image\n        image = cv2.imread(image_path)\n        \n        # Apply the processing function\n        processed_image = plot_func(image)\n        \n        # Plot the processed image\n        plt.subplot(1, num_items, i)\n        plot_cv2_img(processed_image)\n        plt.axis('off')  # Turn off axes\n        plt.title(image_file)  # Add title with image filename\n    \n    plt.tight_layout()  # Adjust layout to avoid overlap of titles\n    plt.show()\n\n# Define a plotting function for OpenCV images\ndef plot_cv2_img(image):\n   \n    # Convert BGR to RGB\n    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    \n    # Display the image\n    plt.imshow(image_rgb)\n    plt.axis('off')  # Turn off axes\n    plt.grid(False)  # Turn off grid\n\n# Function to perform CLAHE on HSV image\ndef clahe_hsv(img):\n   \n    hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n    h, s, v = hsv_img[:,:,0], hsv_img[:,:,1], hsv_img[:,:,2]\n    clahe = cv2.createCLAHE(clipLimit=15.0, tileGridSize=(20,20))\n    v = clahe.apply(v)\n\n    hsv_img = np.dstack((h, s, v))\n\n    rgb = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2RGB)\n    \n    return rgb\n\n# Example usage:\nvid_0_dir = \"../input/tensorflow-great-barrier-reef/train_images/video_0\"\nnum_items1 = 4\nplot_img(vid_0_dir, num_items1, clahe_hsv, \"cv2\")\n","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:49:29.937950Z","iopub.execute_input":"2024-03-23T06:49:29.938329Z","iopub.status.idle":"2024-03-23T06:49:30.997020Z","shell.execute_reply.started":"2024-03-23T06:49:29.938294Z","shell.execute_reply":"2024-03-23T06:49:30.995861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Enhacnement using HSV","metadata":{}},{"cell_type":"code","source":"import numpy as np\n\ndef global_stretching(img_L,height, width):\n    I_min = np.min(img_L)\n    I_max = np.max(img_L)\n    I_mean = np.mean(img_L)\n\n    array_Global_histogram_stretching_L = np.zeros((height, width))\n    for i in range(0, height):\n        for j in range(0, width):\n            p_out = (img_L[i][j] - I_min) * ((1) / (I_max - I_min))\n            array_Global_histogram_stretching_L[i][j] = p_out\n\n    return array_Global_histogram_stretching_L\n\ndef stretching(img):\n    height = len(img)\n    width = len(img[0])\n    for k in range(0, 3):\n        Max_channel  = np.max(img[:,:,k])\n        Min_channel  = np.min(img[:,:,k])\n        for i in range(height):\n            for j in range(width):\n                img[i,j,k] = (img[i,j,k] - Min_channel) * (255 - 0) / (Max_channel - Min_channel)+ 0\n    return img\n\nfrom skimage.color import rgb2hsv,hsv2rgb\nimport numpy as np\n\n\n\ndef  HSVStretching(sceneRadiance):\n    height = len(sceneRadiance)\n    width = len(sceneRadiance[0])\n    img_hsv = rgb2hsv(sceneRadiance)\n    h, s, v = cv2.split(img_hsv)\n    img_s_stretching = global_stretching(s, height, width)\n\n    img_v_stretching = global_stretching(v, height, width)\n\n    labArray = np.zeros((height, width, 3), 'float64')\n    labArray[:, :, 0] = h\n    labArray[:, :, 1] = img_s_stretching\n    labArray[:, :, 2] = img_v_stretching\n    img_rgb = hsv2rgb(labArray) * 255\n\n    \n\n    return img_rgb\n\ndef sceneRadianceRGB(sceneRadiance):\n\n    sceneRadiance = np.clip(sceneRadiance, 0, 255)\n    sceneRadiance = np.uint8(sceneRadiance)\n\n    return sceneRadiance","metadata":{"_kg_hide-input":false,"execution":{"iopub.status.busy":"2024-02-27T04:20:31.118855Z","iopub.execute_input":"2024-02-27T04:20:31.119263Z","iopub.status.idle":"2024-02-27T04:20:31.408140Z","shell.execute_reply.started":"2024-02-27T04:20:31.119217Z","shell.execute_reply":"2024-02-27T04:20:31.407187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def RecoverICM(img1):\n    img = stretching(img1)\n    sceneRadiance = sceneRadianceRGB(img)\n    sceneRadiance = HSVStretching(sceneRadiance)\n    sceneRadiance = sceneRadianceRGB(sceneRadiance)\n    \n    return sceneRadiance\n\n\nvid_0_dir = \"../input/tensorflow-great-barrier-reef/train_images/video_0\"\nnum_items1 = 4\nplot_img(vid_0_dir,num_items1,RecoverICM,\"cv2\")","metadata":{"_kg_hide-input":false,"execution":{"iopub.status.busy":"2024-02-27T04:20:48.366366Z","iopub.execute_input":"2024-02-27T04:20:48.366915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Working Principle using tensorflow:","metadata":{}},{"cell_type":"code","source":"def plot_img_tf(img_dir,num_items,func,mode):\n    img_list = random.sample(os.listdir(img_dir), num_items)\n    full_path = img_dir + '/' + img_list[0]\n    img_temp_plt = plt.imread(full_path)\n    img_temp_cv = cv2.imread(full_path)\n    if mode==\"plt\":\n        \n        img_stack = np.hstack((img_temp_plt,func(img_temp_plt)))\n        plt.figure(figsize=(20,15))\n        plt.imshow(img_stack);\n        plt.title(\"Original Image VS Enhanced Image\",fontsize=25)\n        plt.axis(\"off\")\n        plt.show()\n    if mode==\"cv2\":\n        \n        img_stack = np.hstack((img_temp_cv,func(img_temp_cv)))\n        plt.figure(figsize=(20,15))\n        plt.imshow(img_stack);\n        plt.title(\"Original Image VS Enhanced Image\",fontsize=25)\n        plt.axis(\"off\")\n        plt.show()\n    \n    \n    for i in range(1, len(img_list)):\n        full_path = img_dir + '/' + img_list[i]\n        img_temp_plt = plt.imread(full_path)\n        img_temp_cv = cv2.imread(full_path)\n        if mode==\"plt\":\n            img_stack = np.hstack((img_temp_plt,func(img_temp_plt)));\n            plt.figure(figsize=(20,15))\n            plt.imshow(img_stack);\n            plt.axis(\"off\")\n            plt.show()\n        if mode==\"cv2\":\n            img_stack = np.hstack((img_temp_cv,func(img_temp_cv)));\n            plt.figure(figsize=(20,15))\n            plt.imshow(img_stack);\n            plt.axis(\"off\")\n            plt.show()\n\nimg_dir = \"../input/tensorflow-great-barrier-reef/train_images/video_0\"\nnum_items = 4\nplot_img_tf(img_dir,num_items,tfa.image.equalize,\"plt\")","metadata":{"execution":{"iopub.status.busy":"2024-02-26T07:11:01.572983Z","iopub.execute_input":"2024-02-26T07:11:01.573399Z","iopub.status.idle":"2024-02-26T07:11:04.265207Z","shell.execute_reply.started":"2024-02-26T07:11:01.573357Z","shell.execute_reply":"2024-02-26T07:11:04.264329Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#  Entropy = Average bit rate of Information Caluculation for each Enhanced Image \n","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport cv2\nfrom skimage.feature import greycomatrix\nimg = cv2.imread('/kaggle/input/enhanced-images/Gamma Correction Enhanced Image .png')\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nglcm = np.squeeze(greycomatrix(img, distances=[1],\n                               angles=[0], symmetric=True,\n                               normed=True))\nentropy = -np.sum(glcm*np.log2(glcm + (glcm==0)))\nprint(entropy)","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:57:57.972643Z","iopub.execute_input":"2024-03-23T06:57:57.973001Z","iopub.status.idle":"2024-03-23T06:57:59.223970Z","shell.execute_reply.started":"2024-03-23T06:57:57.972966Z","shell.execute_reply":"2024-03-23T06:57:59.222919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport cv2\nfrom skimage.feature import greycomatrix\nimg = cv2.imread('/kaggle/input/enhanced-images/HSV Enahced image .png')\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nglcm = np.squeeze(greycomatrix(img, distances=[1],\n                               angles=[0], symmetric=True,\n                               normed=True))\nentropy = -np.sum(glcm*np.log2(glcm + (glcm==0)))\nprint(entropy)","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:58:26.619520Z","iopub.execute_input":"2024-03-23T06:58:26.620382Z","iopub.status.idle":"2024-03-23T06:58:26.657533Z","shell.execute_reply.started":"2024-03-23T06:58:26.620335Z","shell.execute_reply":"2024-03-23T06:58:26.656300Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport cv2\nfrom skimage.feature import greycomatrix\nimg = cv2.imread('/kaggle/input/enhanced-images/Scene Radiance output image .png')\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nglcm = np.squeeze(greycomatrix(img, distances=[1],\n                               angles=[0], symmetric=True,\n                               normed=True))\nentropy = -np.sum(glcm*np.log2(glcm + (glcm==0)))\nprint(entropy)","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:58:41.761199Z","iopub.execute_input":"2024-03-23T06:58:41.761576Z","iopub.status.idle":"2024-03-23T06:58:41.794972Z","shell.execute_reply.started":"2024-03-23T06:58:41.761541Z","shell.execute_reply":"2024-03-23T06:58:41.793726Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport cv2\nfrom skimage.feature import greycomatrix\nimg = cv2.imread('/kaggle/input/enhanced-images/Tensor flow Enhance Image .png')\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nglcm = np.squeeze(greycomatrix(img, distances=[1],\n                               angles=[0], symmetric=True,\n                               normed=True))\nentropy = -np.sum(glcm*np.log2(glcm + (glcm==0)))\nprint(entropy)","metadata":{"execution":{"iopub.status.busy":"2024-03-23T06:59:07.519765Z","iopub.execute_input":"2024-03-23T06:59:07.520352Z","iopub.status.idle":"2024-03-23T06:59:07.562589Z","shell.execute_reply.started":"2024-03-23T06:59:07.520315Z","shell.execute_reply":"2024-03-23T06:59:07.561319Z"},"trusted":true},"execution_count":null,"outputs":[]}]}