{"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":"none","dataSources":[{"sourceId":4104,"databundleVersionId":46661,"sourceType":"competition"}],"dockerImageVersionId":30732,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!ls /kaggle/input","metadata":{"execution":{"iopub.status.busy":"2024-06-15T22:40:05.470032Z","iopub.execute_input":"2024-06-15T22:40:05.470465Z","iopub.status.idle":"2024-06-15T22:40:06.496586Z","shell.execute_reply.started":"2024-06-15T22:40:05.470404Z","shell.execute_reply":"2024-06-15T22:40:06.49525Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Crear directorios para extraer los archivos\n!mkdir -p /kaggle/working/train\n\n# Extraer archivos de entrenamiento\n!7z x /kaggle/input/diabetic-retinopathy-detection/train.zip.001 -o/kaggle/working/train\n\n\n# Extraer archivo trainLabels.csv.zip\n!7z x /kaggle/diabetic-retinopathy-detection/trainLabels.csv.zip -o/kaggle/working\n","metadata":{"execution":{"iopub.status.busy":"2024-06-25T04:45:02.089149Z","iopub.execute_input":"2024-06-25T04:45:02.0896Z","iopub.status.idle":"2024-06-25T04:45:12.529633Z","shell.execute_reply.started":"2024-06-25T04:45:02.089566Z","shell.execute_reply":"2024-06-25T04:45:12.528307Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport glob\nimport matplotlib.pyplot as plt\nimport cv2\nfrom tensorflow.keras.utils import to_categorical\nfrom skimage.io import imread\nimport os\nimport numpy as np","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-06-25T04:47:22.887334Z","iopub.execute_input":"2024-06-25T04:47:22.88848Z","iopub.status.idle":"2024-06-25T04:47:22.894649Z","shell.execute_reply.started":"2024-06-25T04:47:22.888435Z","shell.execute_reply":"2024-06-25T04:47:22.893319Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def scaleRadius(img, scale):\n    x = img[img.shape[0] // 2, :, :].sum(1)\n    r = (x > x.mean() / 10).sum() / 2\n    s = scale * 1.0 / r\n    return cv2.resize(img, (0, 0), fx=s, fy=s)\n\ndef preprocess_retinopathy(image_path, scale):\n    a = cv2.imread(image_path)\n    if a is None:\n        return None\n    # Scale image to a given radius\n    a = scaleRadius(a, scale)\n    # Subtract local mean color\n    a = cv2.addWeighted(a, 4, cv2.GaussianBlur(a, (0, 0), scale /30),-4, 128)\n    # Remove outer 10%\n    b = np.zeros(a.shape, dtype=np.uint8)\n    cv2.circle(b, (a.shape[1] // 2, a.shape[0] // 2), int(scale * 0.9), (1, 1, 1), -1, 8, 0)\n    a = a * b + 128 * (1 - b)\n    return a\n\n# Procesar y mostrar una imagen de retinopatía diabética\nimage_files = glob.glob(\"train/train/*.jpeg\")\nif image_files:\n    processed_image_retinopathy = preprocess_retinopathy(image_files[8], 300)\n    if processed_image_retinopathy is not None:\n        plt.figure(figsize=(15, 5))\n        plt.subplot(1, 1, 1)\n        plt.title(\"Processed Retinopathy Image\")\n        plt.imshow(cv2.cvtColor(processed_image_retinopathy, cv2.COLOR_BGR2RGB))\n        plt.axis('off')\n        plt.show()\n    else:\n        print(\"Error al procesar la imagen de retinopatía diabética.\")\nelse:\n    print(\"No se encontraron imágenes en el directorio 'train'.\")\n","metadata":{"execution":{"iopub.status.busy":"2024-06-25T05:15:50.768721Z","iopub.execute_input":"2024-06-25T05:15:50.769215Z","iopub.status.idle":"2024-06-25T05:15:51.24679Z","shell.execute_reply.started":"2024-06-25T05:15:50.769171Z","shell.execute_reply":"2024-06-25T05:15:51.245601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def preprocess_macular_retinopathy(image_path, scale):\n    def scaleRadius(img, scale):\n        x = img[img.shape[0] // 2, :, :].sum(1)\n        r = (x > x.mean() / 10).sum() / 2\n        s = scale * 1.0 / r\n        return cv2.resize(img, (0, 0), fx=s, fy=s)\n\n    def preprocess_image(img):\n        # Seleccionar el canal verde de la imagen\n        img_green = img[:, :, 1]\n\n        # Aplicar CLAHE al canal verde\n        clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n        img_clahe = clahe.apply(img_green)\n\n        # Sustraer el color promedio local\n        img_clahe = cv2.addWeighted(img_clahe, 4, cv2.GaussianBlur(img_clahe, (0, 0), scale / 30), -4, 128)\n\n        return img_clahe\n\n    # Leer y escalar la imagen\n    a = cv2.imread(image_path)\n    if a is None:\n        return None\n    a = scaleRadius(a, scale)\n\n    # Aplicar el preprocesamiento\n    a = preprocess_image(a)\n\n    # Eliminar el 10% exterior\n    b = np.zeros(a.shape, dtype=np.uint8)\n    cv2.circle(b, (a.shape[1] // 2, a.shape[0] // 2), int(scale * 0.9), (1, 1, 1), -1, 8, 0)\n    a = a * b + 128 * (1 - b)\n    \n    return a\n\n# Procesar y mostrar una imagen de degeneración macular y retinopatía diabética\nimage_files = glob.glob(\"train/train/*.jpeg\")\nif image_files:\n    processed_image_macular = preprocess_macular_retinopathy(image_files[8], 300)\n    if processed_image_macular is not None:\n        plt.figure(figsize=(15, 5))\n        plt.subplot(1, 1, 1)\n        plt.title(\"Processed Macular Image\")\n        plt.imshow(processed_image_macular, cmap='gray')\n        plt.axis('off')\n        plt.show()\n    else:\n        print(\"Error al procesar la imagen de degeneración macular.\")\nelse:\n    print(\"No se encontraron imágenes en el directorio 'train'.\")\n","metadata":{"execution":{"iopub.status.busy":"2024-06-25T05:06:30.315895Z","iopub.execute_input":"2024-06-25T05:06:30.317064Z","iopub.status.idle":"2024-06-25T05:06:30.733897Z","shell.execute_reply.started":"2024-06-25T05:06:30.317013Z","shell.execute_reply":"2024-06-25T05:06:30.732741Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def scaleRadius(img, scale):\n    x = img[img.shape[0] // 2, :, :].sum(1)\n    r = (x > x.mean() / 10).sum() / 2\n    s = scale * 1.0 / r\n    return cv2.resize(img, (0, 0), fx=s, fy=s)\n\ndef applyCLAHE(image):\n    # Convert to LAB color space\n    lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)\n    l, a, b = cv2.split(lab)\n    # Apply CLAHE to the L channel\n    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n    cl = clahe.apply(l)\n    # Merge the CLAHE enhanced L channel with a and b channels\n    limg = cv2.merge((cl, a, b))\n    # Convert back to BGR color space\n    final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)\n    return final\n\ndef preprocess_retinopathy(image_path, scale):\n    a = cv2.imread(image_path)\n    if a is None:\n        return None\n    # Scale image to a given radius\n    a = scaleRadius(a, scale)\n    # Subtract local mean color\n    a = cv2.addWeighted(a, 4, cv2.GaussianBlur(a, (0, 0), scale / 30), -4, 128)\n    # Remove outer 10%\n    b = np.zeros(a.shape, dtype=np.uint8)\n    cv2.circle(b, (a.shape[1] // 2, a.shape[0] // 2), int(scale * 0.9), (1, 1, 1), -1, 8, 0)\n    a = a * b + 128 * (1 - b)\n    # Apply CLAHE\n    a = applyCLAHE(a)\n    return a\n\n# Procesar y mostrar una imagen de retinopatía diabética\nimage_files = glob.glob(\"train/train/*.jpeg\")\nif image_files:\n    processed_image_retinopathy = preprocess_retinopathy(image_files[8], 300)\n    if processed_image_retinopathy is not None:\n        plt.figure(figsize=(15, 5))\n        plt.subplot(1, 1, 1)\n        plt.title(\"Processed Retinopathy Image\")\n        plt.imshow(cv2.cvtColor(processed_image_retinopathy, cv2.COLOR_BGR2RGB))\n        plt.axis('off')\n        plt.show()\n    else:\n        print(\"Error al procesar la imagen de retinopatía diabética.\")\nelse:\n    print(\"No se encontraron imágenes en el directorio 'train'.\")\n","metadata":{"execution":{"iopub.status.busy":"2024-06-25T05:06:18.725478Z","iopub.execute_input":"2024-06-25T05:06:18.725898Z","iopub.status.idle":"2024-06-25T05:06:19.165139Z","shell.execute_reply.started":"2024-06-25T05:06:18.725865Z","shell.execute_reply":"2024-06-25T05:06:19.163969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### No usar porque aún estoy explorando lo de tophat y blackhat","metadata":{}},{"cell_type":"code","source":"import cv2\nimport numpy as np\nimport glob\nimport matplotlib.pyplot as plt\n\ndef scaleRadius(img, scale):\n    x = img[img.shape[0] // 2, :, :].sum(1)\n    r = (x > x.mean() / 10).sum() / 2\n    s = scale * 1.0 / r\n    return cv2.resize(img, (0, 0), fx=s, fy=s)\n\ndef applyCLAHE(image):\n    # Convert to LAB color space\n    lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)\n    l, a, b = cv2.split(lab)\n    # Apply CLAHE to the L channel\n    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n    cl = clahe.apply(l)\n    # Merge the CLAHE enhanced L channel with a and b channels\n    limg = cv2.merge((cl, a, b))\n    # Convert back to BGR color space\n    final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)\n    return final\n\ndef denoise(image):\n    # Apply a median filter to reduce noise\n    median_filtered = cv2.medianBlur(image, 5)\n    # Apply a Gaussian filter for low pass filtering\n    low_pass_filtered = cv2.GaussianBlur(median_filtered, (3, 3), 0)\n    return low_pass_filtered\n\ndef morphologicalProcessing(image):\n    # Convert to grayscale\n    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    # Apply top-hat transformation\n    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 10))\n    tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, kernel)\n    # Apply black-hat transformation\n    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))\n    blackhat = cv2.morphologyEx(gray, cv2.MORPH_BLACKHAT, kernel)\n    # Combine original image with transformations\n    add_tophat = cv2.add(gray, tophat)\n    subtract_blackhat = cv2.subtract(add_tophat, blackhat)\n    # Convert back to BGR\n    result = cv2.cvtColor(subtract_blackhat, cv2.COLOR_GRAY2BGR)\n    return result\n\ndef preprocess_retinopathy(image_path, scale):\n    a = cv2.imread(image_path)\n    if a is None:\n        return None\n    # Scale image to a given radius\n    a = scaleRadius(a, scale)\n    # Subtract local mean color\n    a = cv2.addWeighted(a, 4, cv2.GaussianBlur(a, (0, 0), scale / 30), -4, 128)\n    # Remove outer 10%\n    b = np.zeros(a.shape, dtype=np.uint8)\n    cv2.circle(b, (a.shape[1] // 2, a.shape[0] // 2), int(scale * 0.85), (1, 1, 1), -1, 8, 0)\n    a = a * b + 128 * (1 - b)\n    # Apply CLAHE\n    a = applyCLAHE(a)\n    # Denoise the image\n    a = denoise(a)\n    # Apply morphological processing\n    a = morphologicalProcessing(a)\n    return a\n\n# Procesar y mostrar una imagen de retinopatía diabética\nimage_files = glob.glob(\"train/train/*.jpeg\")\nif image_files:\n    processed_image_retinopathy = preprocess_retinopathy(image_files[8], 300)\n    if processed_image_retinopathy is not None:\n        plt.figure(figsize=(15, 5))\n        plt.subplot(1, 1, 1)\n        plt.title(\"Processed Retinopathy Image\")\n        plt.imshow(cv2.cvtColor(processed_image_retinopathy, cv2.COLOR_BGR2RGB))\n        plt.axis('off')\n        plt.show()\n    else:\n        print(\"Error al procesar la imagen de retinopatía diabética.\")\nelse:\n    print(\"No se encontraron imágenes en el directorio 'train'.\")\n","metadata":{"execution":{"iopub.status.busy":"2024-06-25T05:10:40.366728Z","iopub.execute_input":"2024-06-25T05:10:40.367249Z","iopub.status.idle":"2024-06-25T05:10:40.826151Z","shell.execute_reply.started":"2024-06-25T05:10:40.367208Z","shell.execute_reply":"2024-06-25T05:10:40.82471Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}