{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":67836,"databundleVersionId":7527339,"sourceType":"competition"},{"sourceId":7457572,"sourceType":"datasetVersion","datasetId":4332119}],"dockerImageVersionId":30648,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## Introduction\n\nWelcome to our image preprocessing notebook! In this guide, we'll explore techniques to enhance image quality and clarity for improved analysis. By applying methods like Histogram Equalization, CLAHE, and Gamma Correction, we can adjust brightness, contrast, and overall appearance, making images more suitable for various applications.\n\n- **[Histogram Equalization](#Apply-Histogram-Equalizer)**: Adjusts image contrast and brightness by redistributing pixel intensities.\n- **[CLAHE (Contrast Limited Adaptive Histogram Equalization)](#Apply-CLAHE)**: Enhances local contrast, particularly useful for images with varying illumination.\n- **[Gamma Correction](#Apply-Gamma-Correction)**: Adjusts brightness and contrast using a nonlinear transformation, improving image visibility.-\n\nThese preprocessing techniques are essential for tasks like **medical imaging, satellite analysis, and computer vision**. Follow along with our Python implementations using OpenCV and NumPy to see how these methods can elevate your image processing workflows! ","metadata":{}},{"cell_type":"code","source":"# import libs ...\n\nimport os\nimport random\nimport matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom scipy.linalg import fractional_matrix_power\nimport shutil\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Read Image","metadata":{}},{"cell_type":"code","source":"!rm -r /kaggle/working\n!mkdir -p /kaggle/working/temp","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# necessary functions \ndef showImage(img_object):\n    img_rgb = cv2.cvtColor(img_object, cv2.COLOR_BGR2RGB)\n    plt.imshow(img_rgb)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# input images ...\nbase_path = '/kaggle/input/dl-enigma-10-sust-cse-carnival-2024/dlenigma1/BadODD/images/test/'\nimages = os.listdir(base_path)\n\n# random image id ...\nri = np.random.randint(0, len(images))\nprint(images[ri])\nimg_path =base_path + images[ri]\n\n# read image ...\nimg_obj = cv2.imread(img_path, cv2.IMREAD_COLOR)\n\n# show image ...\nshowImage(img_obj)\n\n# dict to save img and hist\nimg_arr = {}\nhist_arr = {}","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Apply Histogram Equalizer\n\nHistogram equalization is a widely used technique in **image processing** that enhances the **contrast** of an image by redistributing pixel intensities. It works by transforming the intensity values of pixels in an image so that the **histogram** of the output image is approximately **flat**. This means that the intensities are spread out over the entire range of possible values, resulting in a more balanced distribution of pixel values.\n\n**What it does:** \n\n Histogram equalization improves the visual appearance of images by stretching the **intensity range**, making details more visible and enhancing the overall **contrast**. It is particularly effective for images with **low contrast** or those that appear **washed out**.\n\n**How it is done:**\n1. **Calculate the Histogram:** First, calculate the histogram of the input image, which represents the frequency of occurrence of each pixel **intensity value**.\n2. **Compute the Cumulative Distribution Function (CDF):** Next, compute the cumulative distribution function of the histogram, which represents the cumulative sum of pixel intensities.\n3. **Normalize the CDF:** Normalize the CDF to scale it to the range [0, 255] if necessary.\n4. **Map Pixel Intensities:** Finally, map the pixel intensities of the input image to new intensity values using the normalized CDF. This transformation redistributes the intensity values to achieve a more uniform distribution, thereby improving the **contrast** of the image.\n\nHistogram equalization is a simple yet powerful technique commonly used for preprocessing images in various **computer vision** and **image processing** applications, including **image enhancement**, **feature extraction**, and **object detection**.\n\n![image.png](https://www.tutorialspoint.com/dip/images/equalize5.jpg)","metadata":{}},{"cell_type":"code","source":"# draw hist plot  ...\ngray_img = cv2.cvtColor(img_obj, cv2.COLOR_BGR2GRAY)\nhist_gray = cv2.calcHist([img_obj], [0], None, [256], [0,256])\n\n### COLOR ###\n\n# convert to HSV color scale\nimg_hsv = cv2.cvtColor(img_obj, cv2.COLOR_BGR2HSV)\nh, s, v = cv2.split(img_hsv)\n\n# historgram Equilization ...\nv = cv2.equalizeHist(v)\nmerged_hsv = cv2.merge((h,s,v))\nbgr_enhanced = cv2.cvtColor(merged_hsv, cv2.COLOR_HSV2BGR)\nhist_HE = cv2.calcHist([v], [0], None, [256], [0,256])\n\n### COLOR ###\n\n### GRAY ###\n\n# bgr_enhanced = cv2.equalizeHist(gray_img)\n# hist_HE = cv2.calcHist([bgr_enhanced], [0], None, [256], [0,256])\n\n### GRAY ###\n\nimg_arr['normal'] = img_obj\nimg_arr['HE_enhanced'] = bgr_enhanced\n\nhist_arr['normal'] = hist_gray\nhist_arr['HE_enhanced'] = hist_HE\n\nprint('HE Done')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Apply CLAHE \n\n**Contrast Limited Adaptive Histogram Equalization (CLAHE)** is an advanced image enhancement technique that improves **contrast** and enhances details in images. Here's a simplified comparison with traditional **Histogram Equalization (HE)** and a brief overview of how to implement **CLAHE**:\n\n<!-- **Comparison with HE:**\n- HE enhances the contrast of an entire image uniformly, which can lead to over-amplification of noise in regions with already high contrast.\n- **CLAHE** divides the image into small tiles and applies histogram equalization to each tile individually. This localized approach prevents over-amplification of noise and preserves details in both low and high-contrast regions.\n\n**How to Implement CLAHE:**\n1. **Divide the Image into Tiles:** Break the image into smaller tiles or blocks.\n2. **Apply Histogram Equalization to Each Tile:** Perform histogram equalization separately on each tile to enhance local contrast.\n3. **Clip the Pixel Values:** Limit the amplification of pixel values above a certain threshold to prevent over-enhancement and maintain natural-looking images.\n4. **Combine the Tiles:** Reassemble the tiles to reconstruct the final enhanced image.\n\nBy implementing **CLAHE**, you can effectively enhance image **contrast** and details while avoiding the drawbacks of traditional histogram equalization. This technique is particularly useful for improving the visual quality of medical images, satellite imagery, and photographs with uneven lighting conditions.\n -->\n![image.png](https://www.researchgate.net/publication/320402762/figure/fig12/AS:549665243840517@1508061814832/A-Green-Channel-B-after-histogram-equalization-C-after-CLAHE.png)\n\n```\n(a) Green Channel\n(b) after Histogram Equilization (HE)\n(c) Contrast Limited Adaptive Histogram Equalization (CLAHE)\n```","metadata":{}},{"cell_type":"code","source":"### COLOR (HSV) ###\n\nimg_hsv = cv2.cvtColor(img_obj, cv2.COLOR_BGR2HSV)\nh, s, v = cv2.split(img_hsv)\n\n# Contrast Limited Adaptive HE ...\nclahe = cv2.createCLAHE(clipLimit = 5, tileGridSize=(8, 8))\nv = clahe.apply(v)\nhist_CLAHE = cv2.calcHist([v], [0], None, [256], [0,256])\nmerged_hsv = cv2.merge((h,s,v))\nbgr_enhanced_1 = cv2.cvtColor(merged_hsv, cv2.COLOR_HSV2BGR)\n\n### COLOR (HSV) ###\n\n\n### COLOR (LAB) ###\n\n# Convert the image to LAB color space\nlab = cv2.cvtColor(img_obj, cv2.COLOR_BGR2LAB)\n\n# Split the LAB image into L, A, and B channels\nl, a, b = cv2.split(lab)\n\n# Apply CLAHE to the L channel\nclahe = cv2.createCLAHE(clipLimit=5, tileGridSize=(8, 8))\nl_clahe = clahe.apply(l)\n\n# Merge the CLAHE-enhanced L channel with the original A and B channels\nlab_clahe = cv2.merge((l_clahe, a, b))\n\n# Convert the LAB image back to BGR color space\nbgr_enhanced_2 = cv2.cvtColor(lab_clahe, cv2.COLOR_LAB2BGR)\n\n### COLOR (LAB) ###\n\n\n### COLOR (RGB) ###\n\nclahe_model = cv2.createCLAHE(clipLimit = 5, tileGridSize=(8,8))\n\n# For ease of understanding, we explicitly equalize each channel individually\ncolorimage_b = clahe_model.apply(img_obj[:,:,0])\ncolorimage_g = clahe_model.apply(img_obj[:,:,1])\ncolorimage_r = clahe_model.apply(img_obj[:,:,2])\n\nbgr_enhanced_3 = np.stack((colorimage_b,colorimage_g,colorimage_r), axis=2)\n\n### COLOR (RGB) ###\n\n\n\n### GRAY ###\n\n# clahe = cv2.createCLAHE(clipLimit = 5)\n# bgr_enhanced = clahe.apply(gray_img)\n# hist_CLAHE = cv2.calcHist([bgr_enhanced], [0], None, [256], [0,256])\n\n### GRAY ###\n\nimg_arr['clahe_enhanced_HSV'] = bgr_enhanced_1\nimg_arr['clahe_enhanced_LAB'] = bgr_enhanced_2\nimg_arr['clahe_enhanced_RGB'] = bgr_enhanced_3\nhist_arr['clahe_enhanced'] = hist_CLAHE\n\nprint('CLAHE Done')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Apply Gamma Correction\n\n**Gamma correction** is a simple yet powerful way to adjust the brightness and contrast of images using Python. Instead of just brightening or darkening an image evenly, gamma correction lets you fine-tune these changes to make your images look better.\n\n**Description:**\n- Imagine gamma correction as a special tool to tweak the brightness and contrast of your photos in a more precise way.\n- It works like a magic wand that can make dark areas brighter without washing out the bright parts or make bright areas darker without losing detail.\n- By adjusting the gamma value, you can control how strong the effect is. A lower gamma value (like 0.5) brightens the image, while a higher value (like 2.0) darkens it.\n\n**How to Do It with Python:**\n1. **Get the Gamma Value:** Decide how much you want to adjust the brightness and contrast. This is your gamma value.\n2. **Apply Gamma Correction:** With Python, it's easy! Just use a simple formula like `output_pixel = input_pixel ** gamma`.\n3. **Normalize the Pixels:** Make sure the pixel values stay within the correct range (usually 0 to 255 for images).\n4. **See the Results:** View or save your image to see how gamma correction has improved its brightness and contrast.\n\nGamma correction is a handy tool for enhancing your images and making them look their best. With just a few lines of Python code, you can give your photos that extra pop and clarity they need.\n\n![image.png](https://www.artleds.com/images/compressed/IC/gamma-curve-of-1-0-2-2-2-5.jpg)","metadata":{}},{"cell_type":"code","source":"def image_agcwd(img, a=0.25):\n    h,w = img.shape[:2]\n    hist,bins = np.histogram(img.flatten(),256,[0,256])\n    cdf = hist.cumsum()\n    cdf_normalized = cdf / cdf.max()\n    prob_normalized = hist / hist.sum()\n\n    unique_intensity = np.unique(img)\n    intensity_max = unique_intensity.max()\n    intensity_min = unique_intensity.min()\n    prob_min = prob_normalized.min()\n    prob_max = prob_normalized.max()\n    \n    pn_temp = (prob_normalized - prob_min) / (prob_max - prob_min)\n    pn_temp[pn_temp>0] = prob_max * (pn_temp[pn_temp>0]**a)\n    pn_temp[pn_temp<0] = prob_max * (-((-pn_temp[pn_temp<0])**a))\n    prob_normalized_wd = pn_temp / pn_temp.sum() # normalize to [0,1]\n    cdf_prob_normalized_wd = prob_normalized_wd.cumsum()\n    inverse_cdf = 1 - cdf_prob_normalized_wd\n    \n    img_new = img.copy()\n    for i in unique_intensity:\n        img_new[img==i] = np.round(255 * (i / 255)**inverse_cdf[i])\n\n#     plt.plot(inverse_cdf, color = 'b')\n#     plt.show()\n    \n    return img_new\n\ndef image_agcwd_truncated(img, a=0.75):\n    h,w = img.shape[:2]\n    hist,bins = np.histogram(img.flatten(),256,[0,256])\n    cdf = hist.cumsum()\n    cdf_normalized = cdf / cdf.max()\n    prob_normalized = hist / hist.sum()\n\n    unique_intensity = np.unique(img)\n    intensity_max = unique_intensity.max()\n    intensity_min = unique_intensity.min()\n    prob_min = prob_normalized.min()\n    prob_max = prob_normalized.max()\n    \n    pn_temp = (prob_normalized - prob_min) / (prob_max - prob_min)\n    pn_temp[pn_temp>0] = prob_max * (pn_temp[pn_temp>0]**a)\n    pn_temp[pn_temp<0] = prob_max * (-((-pn_temp[pn_temp<0])**a))\n    prob_normalized_wd = pn_temp / pn_temp.sum() # normalize to [0,1]\n    cdf_prob_normalized_wd = prob_normalized_wd.cumsum()\n    inverse_cdf = np.maximum(0.5,1 - cdf_prob_normalized_wd)\n    \n    img_new = img.copy()\n    for i in unique_intensity:\n        img_new[img==i] = np.round(255 * (i / 255)**inverse_cdf[i])\n   \n#     plt.plot(prob_normalized_wd, color = 'b')\n#     plt.ylim([0,0.2])\n#     plt.show()\n    \n    return img_new\n\ndef process_bright(img):\n    img_negative = 255 - img\n#     plt.imshow(img_negative, cmap='gray')\n#     plt.title('Negative Image')\n#     plt.show()\n    \n    agcwd = image_agcwd(img_negative)\n    reversed = 255 - agcwd\n    return reversed\n\ndef process_dimmed(img):\n    agcwd = image_agcwd_truncated(img)\n    return agcwd\n\n# == implementation ...\nrgb = cv2.cvtColor(img_obj,cv2.COLOR_BGR2RGB)\nYCrCb = cv2.cvtColor(img_obj, cv2.COLOR_BGR2YCrCb)\nY = YCrCb[:,:,0]\n# plt.imshow(rgb)\n# plt.title('RGB')\n# plt.show()\n\nthreshold = 0.3\nT_t = 112 # Global average brightness \nM,N = img_obj.shape[:2]\nm_I = np.sum(Y/(M*N)) \nt = (m_I - T_t)/ T_t\n\nprint(t)\n\nimg_output = None\nif t < -threshold:\n    print (\"Dimmed Image\")\n    result = process_dimmed(Y)\n    YCrCb[:,:,0] = result\n    img_output = cv2.cvtColor(YCrCb,cv2.COLOR_YCrCb2RGB)\n    img_arr['ADC_dimmed'] = img_output\n#     plt.imshow(img_output)\n#     plt.title('Output')\n#     plt.show()\n    \nelse:\n    print (\"Bright Image\")\n    result = process_bright(Y)\n    YCrCb[:,:,0] = result\n    img_output = cv2.cvtColor(YCrCb,cv2.COLOR_YCrCb2RGB)\n    img_arr['ADC_bright'] = img_output\n#     plt.imshow(img_output)\n#     plt.title('Output')\n#     plt.show()\n\n# process_bright(img_obj)\nprint(\"ADC Done\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Show Image and Historgram","metadata":{}},{"cell_type":"code","source":"# show images ...\ntotal_images = len(list(img_arr.values()))\nfor i in range(1, total_images+1):\n    plt.figure(figsize=(15,10))\n    plt.subplot(3,3,i)\n    showImage(list(img_arr.values())[i-1])\n    \n    save_path = os.path.join('/kaggle/working/temp', f\"{images[ri].split('.')[0]}_{list(img_arr.keys())[i-1]}.jpg\")\n    cv2.imwrite(save_path, cv2.cvtColor(list(img_arr.values())[i-1], cv2.COLOR_BGR2RGB))\n    \n    plt.text(0.5, 0.95, list(img_arr.keys())[i-1], horizontalalignment='center', verticalalignment='center', transform=plt.gca().transAxes, color='white', fontsize=12)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# show images ...\n# for i in range(1, 4):\n#     plt.figure(figsize=(15,10))\n#     plt.subplot(2,2,i)\n#     plt.plot(list(hist_arr.values())[i-1])\n#     plt.text(0.5, 0.95, list(hist_arr.keys())[i-1], horizontalalignment='center', verticalalignment='center', transform=plt.gca().transAxes, color='black', fontsize=12)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Infer over the modified image","metadata":{}},{"cell_type":"code","source":"!pip install ultralytics -q\nprint('Done')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import yolo model\nfrom ultralytics import YOLO\n\n# Directory path ...\ntest_directory = \"/kaggle/working/temp\"\n\n# Load the model ...\nmodel = model = YOLO(\"/kaggle/input/yolo-models/yolov8_50epoch_cp.3_mxp_.3.pt\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# get prediction boxes string according to the submission format ...\ndef get_prediction_string(boxes, scores, classes):\n    pred_strs = []\n    for i, score in enumerate(scores):\n        single_pred_str = \"\"\n        single_pred_str += str(float(classes[i])) + \" \" + str(float(score)) + \" \"\n        \n        x_center , y_center, width,height = boxes[i]\n        x1 = float(x_center) - (float(width) / 2)\n        y1 = float(y_center) - (float(height) / 2)\n        width = float(width)\n        height = float(height)\n        #single_pred_str += \" \".join(str(float(x)) for x in boxes[i])\n        single_pred_str +=  f\"{x1} {y1} {width} {height}\"\n        \n        pred_strs.append(single_pred_str)\n    ans = ','.join(map(str, pred_strs))\n    if len(ans):\n        return ans\n    return \"0 0 0 0 0 0\"\n\n# get the predcition in id, ImageID, PredictionString_pred foramt ...\ndef get_prediction_entry(i, filename, boxes, scores, classes):\n    return {\n        \"id\": i, # strating from 0 ...\n        \"ImageID\": filename.split('.')[0], # before the extension ...\n        \"PredictionString_pred\": get_prediction_string(boxes, scores, classes)\n    }\n\n# do the inference ...\ndef predict_all_files(test_directory):\n    predictions = []\n    for i,filename in tqdm(enumerate(os.listdir(test_directory))):\n        if filename.endswith(\".jpg\"):\n            filepath = os.path.join(test_directory, filename)\n            results = model.predict(source=filepath, conf=0.50, verbose=False)\n            boxes = results[0].boxes.xywhn\n            scores = results[0].boxes.conf\n            classes = results[0].boxes.cls\n            prediction = get_prediction_entry(i, filename, boxes, scores, classes)\n            predictions.append(prediction)\n            \n# to csv format ...\n    predictions_df = pd.DataFrame(predictions)\n    predictions_df.to_csv(\"submission.csv\", index=False)\n\n# call the inference function ...\npredict_all_files(test_directory)\nprint(\"Done....\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = pd.read_csv('/kaggle/working/submission.csv')\ntest_df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classNames={};\nwith open('/kaggle/input/dl-enigma-10-sust-cse-carnival-2024/dlenigma1/BadODD/badodd.txt') as classes:\n    lines=classes.read();\n    lines=lines.split('\\n');\n    for i in range(len(lines)):\n        line=lines[i];\n        if len(line)==0:\n            continue;\n        classNames[i]=line;\n\n\ndef show_segmentations(_image_id, serial, display=False):\n    filtered_df = test_df[test_df['ImageID'] == _image_id]\n    base_path = '/kaggle/working/temp/' #enter here\n#     print('Image Path: ', base_path + _image_id + '.jpg')\n    image = np.array(Image.open(base_path + _image_id + '.jpg'))\n    class_colors = {\n        0: (255, 0, 0),      # Red\n        1: (0, 255, 0),      # Green\n        2: (0, 0, 255),      # Blue\n        3: (255, 255, 0),    # Yellow\n        4: (0, 255, 255),    # Cyan\n        5: (255, 0, 255),    # Magenta\n        6: (128, 0, 0),      # Dark Red\n        7: (0, 128, 0),      # Dark Green\n        8: (0, 0, 128),      # Dark Blue\n        9: (128, 128, 0),    # Olive\n        10: (0, 128, 128),   # Teal\n        11: (128, 0, 128),   # Purple\n        12: (128, 128, 128)  # Grey\n    }\n    pred_str= test_df['PredictionString_pred'][serial]\n    pred_list = pred_str.split(',')\n    \n    for pred in pred_list:\n        temp = pred.split(' ')\n        _id= int(float(temp[0]))\n        con = temp[1]\n        x_center = float(temp[2])\n        y_center = float(temp[3])\n        width= float(temp[4])\n        height = float(temp[5])\n        class_num = classNames[_id]\n        x_center, y_center, width, height = int(x_center * image.shape[1]), int(y_center * image.shape[0]), int(width * image.shape[1]), int(height * image.shape[0])\n        xmin, ymin = x_center , y_center \n        xmax, ymax = x_center + width , y_center + height\n        color = class_colors[int(_id)]\n        title = str(round(float(con), 2)) + '('+ class_num +')'\n        \n        font_scale = 0.7  \n        font_thickness = 2  \n        cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 2)\n        cv2.putText(image, title, (xmin, ymin - 10), cv2.FONT_HERSHEY_SIMPLEX, font_scale, color, font_thickness)\n        \n    if display:\n        plt.figure(figsize=(15,5))\n        plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n        plt.show()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"total_images = test_df.shape[0]\n\nfor n in range(total_images):\n    print(test_df.ImageID[n])\n    show_segmentations(test_df.ImageID[n], n, True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!rm -rf /kaggle/working/temp","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Create Dataset (CLAHE - GRAY)\n\nBy comparing the image contrast and brightness, I think CLAHE would suit better for Object Detection. Thus I have only provided the implementation of CLAHE Dataset Creation. You can also add other functions to create particular enhanced images","metadata":{}},{"cell_type":"code","source":"# make folders for new dataset ...\n!mkdir -p /kaggle/working/dlenigma1/BadODD/images/test\n!rm -rf /kaggle/working/dlenigma1/BadODD/images/train\n!mkdir -p /kaggle/working/dlenigma1/BadODD/images/train\n!mkdir -p /kaggle/working/dlenigma1/BadODD/labels/train\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# function to create CLAHE_HSV image\ndef calculate_CLAHE_HSV (img_obj, clipLimit=6):\n    \n    img_hsv = cv2.cvtColor(img_obj, cv2.COLOR_BGR2HSV)\n    h, s, v = cv2.split(img_hsv)\n\n    # Contrast Limited Adaptive HE ...\n    clahe = cv2.createCLAHE(clipLimit = clipLimit, tileGridSize=(8, 8))\n    v = clahe.apply(v)\n    hist_CLAHE = cv2.calcHist([v], [0], None, [256], [0,256])\n    merged_hsv = cv2.merge((h,s,v))\n    bgr_enhanced = cv2.cvtColor(merged_hsv, cv2.COLOR_HSV2BGR)\n    \n    return bgr_enhanced\n\n# function to create CLAHE_HSV Gray Image\ndef calculate_CLAHE_HSV_Gray (img_obj, clipLimit=6):\n    \n    gray_img = cv2.cvtColor(img_obj, cv2.COLOR_BGR2GRAY)\n    clahe = cv2.createCLAHE(clipLimit = clipLimit)\n    bgr_enhanced = clahe.apply(gray_img)\n    \n    return bgr_enhanced\n\n\nshowImage(calculate_CLAHE_HSV_Gray(img_obj))     ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# necessary paths...\nbase_train_image_path = '/kaggle/input/dl-enigma-10-sust-cse-carnival-2024/dlenigma1/BadODD/images/train/'\nbase_train_label_path = '/kaggle/input/dl-enigma-10-sust-cse-carnival-2024/dlenigma1/BadODD/labels/train/'\nbase_test_image_path = '/kaggle/input/dl-enigma-10-sust-cse-carnival-2024/dlenigma1/BadODD/images/test/'\n\noutput_train_image_path = '/kaggle/working/dlenigma1/BadODD/images/train/'\noutput_train_label_path = '/kaggle/working/dlenigma1/BadODD/labels/train/'\noutput_test_image_path = '/kaggle/working/dlenigma1/BadODD/images/test/'\n\n# load images\ntrain_images = os.listdir(base_train_image_path)\ntrain_labels = os.listdir(base_train_label_path)\ntest_images = os.listdir(base_test_image_path)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# make test dataset ...\nprint(\"Total Test Image: \", len(os.listdir(base_test_image_path)))\nfor image in tqdm(test_images):\n    \n    img_path = base_test_image_path + image\n    image_obj = cv2.imread(img_path, cv2.IMREAD_COLOR)\n#     enhanced_img = calculate_CLAHE_HSV(image_obj)  # for color image\n    enhanced_img = calculate_CLAHE_HSV_Gray (image_obj)  # for gray image\n    \n    \n    # new file path\n    image_name, image_ext = image.split('.')\n    new_file_path = output_test_image_path + image_name + '_clahe.' + image_ext\n    cv2.imwrite(new_file_path, cv2.cvtColor(enhanced_img, cv2.COLOR_BGR2RGB))\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# check if image copied correctly ...\nimg_path = output_test_image_path + os.listdir(output_test_image_path)[155]\nimg_obj = cv2.imread(img_path, cv2.IMREAD_COLOR)\nplt.imshow(img_obj)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # make train dataset ...\nprint(\"Total Train Image: \", len(os.listdir(base_train_label_path)))\nfor image in tqdm(train_images):\n    \n    img_path = base_train_image_path + image\n    \n    image_obj = cv2.imread(img_path, cv2.IMREAD_COLOR)\n#     enhanced_img = calculate_CLAHE_HSV(image_obj)  # for color image\n    enhanced_img = calculate_CLAHE_HSV_Gray(image_obj)  # for gray image\n    \n    # new file path\n    image_name, image_ext = image.split('.')\n    new_file_path = output_train_image_path + image_name + '_clahe.' + image_ext\n    cv2.imwrite(new_file_path, cv2.cvtColor(enhanced_img, cv2.COLOR_BGR2RGB))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# check image copied correctly ...'\nprint(len(os.listdir(output_train_image_path)))\nimg_path = output_train_image_path + os.listdir(output_train_image_path)[1]\nimg_obj = cv2.imread(img_path, cv2.IMREAD_COLOR)\nplt.imshow(img_obj)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# copy labels ...\nprint(\"Total Train Labels: \", len(os.listdir(base_train_label_path)))\n\nfor label in tqdm(train_labels):\n    \n    shutil.copy(os.path.join(base_train_label_path, label), os.path.join(output_train_label_path, label))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(os.listdir('/kaggle/working/dlenigma1/BadODD/labels/train/')[1])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!tree -d","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Compression started...')\n\n\n!zip -r clahe_enhanced_gray_images.zip dlenigma1 -q\nprint('Compression Done')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from IPython.display import FileLink \nFileLink(r'clahe_enhanced_gray_images.zip')","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}