{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":14774,"databundleVersionId":875431,"sourceType":"competition"}],"dockerImageVersionId":30747,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport cv2\nfrom PIL import Image \nimport pandas as pd\nfrom sklearn.model_selection import train_test_split","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-07-24T15:51:51.351749Z","iopub.execute_input":"2024-07-24T15:51:51.352181Z","iopub.status.idle":"2024-07-24T15:51:51.35775Z","shell.execute_reply.started":"2024-07-24T15:51:51.352152Z","shell.execute_reply":"2024-07-24T15:51:51.356794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = os.listdir('/kaggle/input/aptos2019-blindness-detection/train_images')\nprint(dataset[0])\nlabel = pd.read_csv('/kaggle/input/aptos2019-blindness-detection/train.csv')\nprint(len(label))","metadata":{"execution":{"iopub.status.busy":"2024-07-24T15:51:51.727737Z","iopub.execute_input":"2024-07-24T15:51:51.728369Z","iopub.status.idle":"2024-07-24T15:51:51.742068Z","shell.execute_reply.started":"2024-07-24T15:51:51.728336Z","shell.execute_reply":"2024-07-24T15:51:51.740993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img = mpimg.imread('/kaggle/input/aptos2019-blindness-detection/train_images/000c1434d8d7.png')\nimgplot = plt.imshow(img)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-07-24T15:51:52.158715Z","iopub.execute_input":"2024-07-24T15:51:52.159516Z","iopub.status.idle":"2024-07-24T15:51:54.227306Z","shell.execute_reply.started":"2024-07-24T15:51:52.159467Z","shell.execute_reply":"2024-07-24T15:51:54.226321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\n\ndef brightness(pixel):\n    # Calculate the brightness of an RGB pixel\n    return np.sqrt(0.299 * (pixel[0] ** 2) + 0.587 * (pixel[1] ** 2) + 0.114 * (pixel[2] ** 2))\n\ndef crop_image(image_path, threshold=10):\n    # Load the image\n    img = Image.open(image_path)\n    img = img.convert(\"RGB\")  # Ensure image is in RGB format\n    \n    # Convert the image to a numpy array\n    img_array = np.array(img)\n    \n    # Calculate the brightness of each pixel in the middle row\n    middle_row = img_array[img_array.shape[0] // 2]\n    brightness_middle_row = np.apply_along_axis(brightness, 1, middle_row)\n    \n    # Find columns where the pixel brightness in the middle row is above the threshold\n    non_dark_columns = np.where(brightness_middle_row > threshold)[0]\n    if non_dark_columns.size == 0:\n        # If no bright pixel is found, do not crop\n        left, right = 0, img_array.shape[1]\n    else:\n        left = non_dark_columns[0]\n        right = non_dark_columns[-1]\n\n    # Crop the image\n    cropped_img = img.crop((left, 0, right + 1, img.height))\n    \n    return cropped_img\n\ndef augment_image(image):\n    # Define augmentation pipeline\n    transform = A.Compose([\n        A.HorizontalFlip(p=0.5),\n        A.RandomBrightnessContrast(p=0.2),\n        A.RandomRotate90(p=0.5),\n        ToTensorV2()\n    ])\n    \n    # Convert image to numpy array for augmentation\n    img_array = np.array(image)\n    augmented = transform(image=img_array)\n    aug_img = augmented['image']\n    \n    return aug_img\n\n# Example usage\nimage_path = '/kaggle/input/aptos2019-blindness-detection/train_images/014508ccb9cb.png'\ncropped_img = crop_image(image_path)\n\n# Convert to grayscale\ncropped_img_gray = cropped_img.convert(\"L\")\n\n# Apply augmentation\naugmented_img = augment_image(cropped_img_gray)\n\noriginal_img = Image.open(image_path)\nplt.figure(figsize=(15, 10))\nplt.subplot(1, 3, 1)\nplt.title(\"Original Image\")\nplt.imshow(original_img)\nplt.axis('off')\n\nplt.subplot(1, 3, 2)\nplt.title(\"Cropped Grayscale Image\")\nplt.imshow(cropped_img_gray, cmap='gray')\nplt.axis('off')","metadata":{"execution":{"iopub.status.busy":"2024-07-24T16:13:43.203747Z","iopub.execute_input":"2024-07-24T16:13:43.204516Z","iopub.status.idle":"2024-07-24T16:13:43.781386Z","shell.execute_reply.started":"2024-07-24T16:13:43.204479Z","shell.execute_reply":"2024-07-24T16:13:43.780419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = '/kaggle/input/aptos2019-blindness-detection/train_images'\ndata = []\n\nfor imgs in dataset:\n    image = Image.open(path +'/'+ imgs)\n    image = image.resize((256,256))\n    image = image.convert('RGB')\n    image = np.array(image)\n    data.append(image)","metadata":{"execution":{"iopub.status.busy":"2024-07-24T12:33:17.639909Z","iopub.status.idle":"2024-07-24T12:33:17.640252Z","shell.execute_reply.started":"2024-07-24T12:33:17.640089Z","shell.execute_reply":"2024-07-24T12:33:17.640103Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(data))\ndata[0]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data[0].shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = np.array(data)\nY = np.array(label)\nY = np.delete(Y, 0, axis=1)\nprint(X.shape)\nprint(Y.shape)\nprint(Y)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=2)\nprint(X.shape, X_train.shape, X_test.shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train_scaled = X_train/255\n\nX_test_scaled = X_test/255\n\nX_train[0]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train_scaled[0]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_of_classes = 5\n\nmodel = keras.Sequential()\n\nmodel.add(keras.layers.Conv2D(32, kernel_size=(3,3), activation='relu', input_shape=(256,256,3)))\nmodel.add(keras.layers.MaxPooling2D(pool_size=(2,2)))\n\n\nmodel.add(keras.layers.Conv2D(64, kernel_size=(3,3), activation='relu'))\nmodel.add(keras.layers.MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(keras.layers.Flatten())\n\nmodel.add(keras.layers.Dense(128, activation='relu'))\nmodel.add(keras.layers.Dropout(0.5))\n\nmodel.add(keras.layers.Dense(64, activation='softmax'))\nmodel.add(keras.layers.Dropout(0.5))\n\n\nmodel.add(keras.layers.Dense(num_of_classes, activation='sigmoid'))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Y_train = np.array(Y_train, dtype=int)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train_scaled","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])\n\nmodel.fit(X_train_scaled, Y_train, validation_split=0.1, epochs=30)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Y_test = np.array(Y_test, dtype=int)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss, accuracy = model.evaluate(X_test_scaled, Y_test)\nprint('Test Accuracy =', accuracy)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"h = history\n\n# plot the loss value\nplt.plot(h.history['loss'], label='train loss')\nplt.plot(h.history['val_loss'], label='validation loss')\nplt.legend()\nplt.show()\n\n# plot the accuracy value\nplt.plot(h.history['acc'], label='train accuracy')\nplt.plot(h.history['val_acc'], label='validation accuracy')\nplt.legend()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"input_image_path = input('Path of the image to be predicted: ')\n\ninput_image = cv2.imread(input_image_path)\n\ncv2_imshow(input_image)\n\ninput_image_resized = cv2.resize(input_image, (256,256))\n\ninput_image_scaled = input_image_resized/255\n\ninput_image_reshaped = np.reshape(input_image_scaled, [1,256,256,3])\n\ninput_prediction = model.predict(input_image_reshaped)\n\nprint(input_prediction)\n\n\ninput_pred_label = np.argmax(input_prediction)\n\nprint(input_pred_label)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}