{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"colab":{"provenance":[],"collapsed_sections":["Qw7qc1lGyka3","IKJa6fTNy9-X","qrM5DPrVzCcJ"],"machine_shape":"hm","gpuType":"A100"},"accelerator":"GPU","kaggle":{"accelerator":"none","dataSources":[{"sourceId":62057,"databundleVersionId":6714922,"sourceType":"competition"}],"dockerImageVersionId":31012,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# GLASS DETECTION\n\n## INTRODUCTION\n\nGlass detection from images is essential for various applications, including manufacturing quality control, recycling, and environmental monitoring. This process involves identifying glass objects in diverse settings, such as urban areas and waste sorting facilities. Advances in computer vision and deep learning enable efficient automation of this task, minimizing time and human error.\n\n## AIM\n\nThe aim of this project is to utilize a convolutional neural network (CNN) to classify images into two categories: 'Glass' and 'No Glass'. The model will be trained on a dataset of images featuring different objects, with the objective of accurately detecting the presence of glass in each image.\n","metadata":{"id":"8w1V1OLswOo6"}},{"cell_type":"markdown","source":"### IMPORTS","metadata":{"id":"Qw7qc1lGyka3"}},{"cell_type":"code","source":"#pip install opencv-python","metadata":{"id":"kKDRAgkAyo6z"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#!pip install scikit-learn","metadata":{"id":"v4HIIJd5yn1_"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# !pip install --upgrade tensorflow","metadata":{"id":"dvv3eeRGymbw"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nimport warnings\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport re\nfrom sklearn.model_selection import train_test_split\n#from IPython.display import Image\n\nfrom keras.models import Sequential, Model, load_model\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, Input, BatchNormalization, Reshape, GlobalAveragePooling2D,Activation\nfrom keras.regularizers import l2\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions\n\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)","metadata":{"id":"XEiNYUvgwNyL","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T12:18:44.338054Z","iopub.execute_input":"2025-04-21T12:18:44.338582Z","iopub.status.idle":"2025-04-21T12:18:44.344846Z","shell.execute_reply.started":"2025-04-21T12:18:44.338554Z","shell.execute_reply":"2025-04-21T12:18:44.343868Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### READING DATA","metadata":{"id":"IKJa6fTNy9-X"}},{"cell_type":"code","source":"img_path= '/kaggle/input/applications-of-deep-learning-wustl-fall-2023/'","metadata":{"id":"rfeRtq5qyRXM","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T12:21:37.738812Z","iopub.execute_input":"2025-04-21T12:21:37.739135Z","iopub.status.idle":"2025-04-21T12:21:37.742938Z","shell.execute_reply.started":"2025-04-21T12:21:37.739112Z","shell.execute_reply":"2025-04-21T12:21:37.742190Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/applications-of-deep-learning-wustl-fall-2023/train.csv')\ndf.head()","metadata":{"id":"a8uOIOviy5Gw","outputId":"c854a216-b5e4-4d67-eaa6-5ee014927abf","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T12:21:39.443603Z","iopub.execute_input":"2025-04-21T12:21:39.443905Z","iopub.status.idle":"2025-04-21T12:21:39.469852Z","shell.execute_reply.started":"2025-04-21T12:21:39.443884Z","shell.execute_reply":"2025-04-21T12:21:39.469175Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['file'] = df['file'].apply(lambda x: img_path + x)","metadata":{"id":"u7Bal_sWLE1O","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T12:21:52.678328Z","iopub.execute_input":"2025-04-21T12:21:52.678597Z","iopub.status.idle":"2025-04-21T12:21:52.691730Z","shell.execute_reply.started":"2025-04-21T12:21:52.678578Z","shell.execute_reply":"2025-04-21T12:21:52.690855Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['label'] = df['glasses'].apply(lambda x: 'glasses' if x == 1 else 'no_glasses')\ndf.head()","metadata":{"id":"eUTft-aKKxTv","outputId":"41f745d1-9297-4365-f44b-e36c6b421118","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T12:22:00.915680Z","iopub.execute_input":"2025-04-21T12:22:00.916018Z","iopub.status.idle":"2025-04-21T12:22:00.930447Z","shell.execute_reply.started":"2025-04-21T12:22:00.915994Z","shell.execute_reply":"2025-04-21T12:22:00.929516Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.rename(columns={'glasses': 'encoded_label'}, inplace=True)\ndf.rename(columns={'file': 'img'}, inplace=True)","metadata":{"id":"4HxhmvnZMeMo","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T12:22:03.208386Z","iopub.execute_input":"2025-04-21T12:22:03.208725Z","iopub.status.idle":"2025-04-21T12:22:03.214023Z","shell.execute_reply.started":"2025-04-21T12:22:03.208700Z","shell.execute_reply":"2025-04-21T12:22:03.213180Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### EDA","metadata":{"id":"pODuDeh3zyOw"}},{"cell_type":"code","source":"selected_images = df.groupby('encoded_label', as_index=False).apply(lambda x: x.sample(n=3, random_state=1)).reset_index(drop=True)\n\nsns.set(style='whitegrid')\nfig, axes = plt.subplots(2, 3, figsize=(5, 5))\n\naxes = axes.flatten()\n\nfor ax, (img_path, label) in zip(axes, zip(selected_images['img'], selected_images['label'])):\n    img = Image.open(img_path)\n    ax.imshow(img)\n    ax.axis('off')\n    ax.set_title(label, fontsize=14)\n\nplt.tight_layout()\nplt.show()","metadata":{"id":"JBhnT2_szfM8","outputId":"880bfff5-42a8-424f-8a8b-b4124dbee972","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T12:22:05.940912Z","iopub.execute_input":"2025-04-21T12:22:05.941291Z","iopub.status.idle":"2025-04-21T12:22:07.097777Z","shell.execute_reply.started":"2025-04-21T12:22:05.941267Z","shell.execute_reply":"2025-04-21T12:22:07.096881Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label_values = df['label'].value_counts()\nplt.figure(figsize=(3, 3))\nplt.pie(label_values, labels=label_values.index, autopct='%1.1f%%', startangle=90, colors=['skyblue', 'lightcoral'])\nplt.show()","metadata":{"id":"rLOhgjmu1Gki","outputId":"68e340bf-fdcd-47e1-881e-be54df8323da"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### PREPARING TEST DATA","metadata":{"id":"H6V08sBD0DgA"}},{"cell_type":"code","source":"img_width, img_height = 170, 170","metadata":{"id":"weAn5b770HJ5"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x = []\ny = []\n\nfor img_path, label in zip(df['img'], df['encoded_label']):\n    img = cv2.imread(img_path)\n    if img is None:\n        continue\n\n    img = cv2.resize(img, (img_width, img_height))\n    img = img / 255.0\n    x.append(img)\n    y.append(label)","metadata":{"id":"JWqZxPbK0Jol"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x = np.array(x)\ny = np.array(y)","metadata":{"id":"52zZ7jRr0K_h"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=42)","metadata":{"id":"C6EXsB8M0MV_"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## CNN","metadata":{"id":"whi4JmAI2-PR"}},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Input(shape=(img_width,img_height, 3)))\nmodel.add(Conv2D(64, 3, padding='same', activation='relu'))\nmodel.add(MaxPooling2D())\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(64, 3, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D())\nmodel.add(Conv2D(64, 3, padding='same', activation='relu'))\nmodel.add(MaxPooling2D())\n\nmodel.add(Conv2D(128, 3, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, 3, padding='same', activation='relu'))\nmodel.add(MaxPooling2D())\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(256, 3, padding='same', activation='relu'))\nmodel.add(MaxPooling2D())\nmodel.add(Dropout(0.2))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(2, activation='softmax'))\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']);","metadata":{"id":"QZ1TpezR6gxG"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"early_stopping = EarlyStopping(monitor='val_loss', patience=3)\n\nhistory = model.fit(x_train, y_train, epochs=15, validation_data=(x_test, y_test), verbose=1, callbacks=[early_stopping])","metadata":{"id":"rJw6eI_N3Hdb","outputId":"123dbf0a-50cb-4e33-adc2-cfc2ed56f66d"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"id":"3AKOwpEV_bfb","outputId":"1178c364-be63-44c8-fc49-ce2d47b7b2ca"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history_df = pd.DataFrame(history.history)\nhistory_df","metadata":{"id":"CvsXZn7X_3TQ","outputId":"0142dd78-fcf8-4092-cb4d-e7a2f4b91302"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ax = history_df[['accuracy','val_accuracy']].plot(title = \"Train and Validation Accuracies\" , marker='o')\nax.set(xlabel =\"Epochs\", ylabel = \"Accuracy\")\nplt.show()","metadata":{"id":"_mn1p82X_Vng","outputId":"81d735fb-9ebe-4bc3-93ed-c8e2f3a1d2bb"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('Glass_Detection.keras')","metadata":{"id":"A52Rq4EB_JuC"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_size = (img_width, img_height)\ntest_images = df.sample(n=12)\n\nimages = []\npredicted_classes = []\nactual_classes = []\n\nfor index, row in test_images.iterrows():\n    img_path = row['img']\n    actual_class = row['encoded_label']\n    img = image.load_img(img_path, target_size=img_size)\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)\n    img_array /= 255.0\n\n    predictions = model.predict(img_array)\n    predicted_class = np.argmax(predictions, axis=1)\n\n    images.append(img)\n    predicted_classes.append(predicted_class[0])\n    actual_classes.append(actual_class)\n\nclass_labels = {0: 'No Glasses', 1: 'Glasses'}\n\nnum_images = len(images)\ncols = 3\nrows = (num_images // cols) + (num_images % cols > 0)\n\nplt.figure(figsize=(15, rows * 5))\nfor i in range(num_images):\n    plt.subplot(rows, cols, i + 1)\n    plt.imshow(images[i])\n    plt.title(f'Actual: {class_labels[actual_classes[i]]}\\nPredicted: {class_labels[predicted_classes[i]]}')\n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"id":"4BQJ8pv04l7M","outputId":"3261ad59-b229-4795-9587-ee1897f4f54e"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# MODEL TESTING","metadata":{"id":"HeAMXhwJmwVp"}},{"cell_type":"markdown","source":"## READING TEST DATA","metadata":{"id":"KixLPMqcnXLr"}},{"cell_type":"code","source":"img_path= '/kaggle/input/applications-of-deep-learning-wustl-fall-2023/'\n\ndf_test = pd.read_csv('/kaggle/input/applications-of-deep-learning-wustl-fall-2023/test.csv')\ndf_test.head()","metadata":{"id":"lr2fvL3RnZ1j","outputId":"5c0a198f-0754-458c-83a6-33f044c79576","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T12:22:58.229667Z","iopub.execute_input":"2025-04-21T12:22:58.230013Z","iopub.status.idle":"2025-04-21T12:22:58.243861Z","shell.execute_reply.started":"2025-04-21T12:22:58.229979Z","shell.execute_reply":"2025-04-21T12:22:58.242877Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test['file'] = df_test['file'].apply(lambda x: img_path + x)","metadata":{"id":"z7BKw6iDOvuh","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T12:23:00.612871Z","iopub.execute_input":"2025-04-21T12:23:00.613600Z","iopub.status.idle":"2025-04-21T12:23:00.619945Z","shell.execute_reply.started":"2025-04-21T12:23:00.613572Z","shell.execute_reply":"2025-04-21T12:23:00.619177Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test.rename(columns={'file': 'img'}, inplace=True)","metadata":{"id":"AjhogmesO58d","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T12:23:02.479108Z","iopub.execute_input":"2025-04-21T12:23:02.479853Z","iopub.status.idle":"2025-04-21T12:23:02.484035Z","shell.execute_reply.started":"2025-04-21T12:23:02.479825Z","shell.execute_reply":"2025-04-21T12:23:02.483192Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test.head()","metadata":{"id":"tyZ4oZjcPInC","outputId":"484f093c-a7e2-4e28-d995-eb33f2469a48","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T12:23:04.518855Z","iopub.execute_input":"2025-04-21T12:23:04.519163Z","iopub.status.idle":"2025-04-21T12:23:04.526992Z","shell.execute_reply.started":"2025-04-21T12:23:04.519140Z","shell.execute_reply":"2025-04-21T12:23:04.526163Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## PREDICT IMAGES","metadata":{"id":"JiYaelEVqCH7"}},{"cell_type":"code","source":"img_width, img_height = 170, 170","metadata":{"id":"c7cY_uU6qBdB"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x = []\n\nfor img_path in df_test['img']:\n    img = cv2.imread(img_path)\n    if img is None:\n        continue\n\n    img = cv2.resize(img, (img_width, img_height))\n    img = img / 255.0\n    x.append(img)","metadata":{"id":"xlMvqzHoqGqN"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_test = np.array(x)","metadata":{"id":"XPT_LlTdq4Rh"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions=model.predict(x_test)\npredictions=predictions.argmax(axis=-1)\npredictions=np.array(predictions)","metadata":{"id":"ZZxYoWzbq7CB","outputId":"7b5e2603-487c-454f-e284-831a6e40f0e5"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# SUBMIT MODEL","metadata":{"id":"6EG4YqXfmg2V"}},{"cell_type":"code","source":"submission=pd.DataFrame({\n    'id':df_test['id'],\n    'glasses':predictions\n})","metadata":{"id":"Cf2WRuBUmghB"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.head()","metadata":{"id":"I4w-RAuMq_Za","outputId":"f9232e6f-d3d5-4047-933b-d0e59549b5a8"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.to_csv('submission.csv',index=False)","metadata":{"id":"Rc0-cVl8rAqh"},"outputs":[],"execution_count":null}]}