{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":62057,"databundleVersionId":6714922,"sourceType":"competition"}],"dockerImageVersionId":30887,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Glass Detection","metadata":{}},{"cell_type":"markdown","source":"## Introduction\n\nGlass detection from images is a crucial task in many real-world applications, including manufacturing quality control, recycling, and environmental monitoring. The process involves identifying glass objects in various settings, such as urban environments, industrial sites, and waste sorting facilities. With the advancements in computer vision and deep learning techniques, it is now possible to automate this process efficiently, saving time and reducing human error.\n\nIn this project, we use a convolutional neural network (CNN) to classify images into two categories: 'Glass' and 'No Glass'. The model is trained on a dataset containing images of different objects, with the goal of accurately detecting the presence of glass in each image.","metadata":{}},{"cell_type":"markdown","source":"## Requirements","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom tensorflow.keras.datasets import cifar10\nimport cv2\nimport pandas as pd\nimport os \nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten, Input, MaxPooling2D,Dropout,BatchNormalization,Reshape\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten, Input, MaxPooling2D,Dropout,BatchNormalization,Reshape\nfrom sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom sklearn.metrics import accuracy_score\nimport math\nfrom tensorflow.keras.models import load_model","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:33:12.782475Z","iopub.execute_input":"2025-02-15T09:33:12.782654Z","iopub.status.idle":"2025-02-15T09:33:25.828105Z","shell.execute_reply.started":"2025-02-15T09:33:12.782634Z","shell.execute_reply":"2025-02-15T09:33:25.827212Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Import Data","metadata":{}},{"cell_type":"code","source":"df=pd.read_csv(\"/kaggle/input/applications-of-deep-learning-wustl-fall-2023/train.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:34:16.657692Z","iopub.execute_input":"2025-02-15T09:34:16.657985Z","iopub.status.idle":"2025-02-15T09:34:16.678856Z","shell.execute_reply.started":"2025-02-15T09:34:16.657964Z","shell.execute_reply":"2025-02-15T09:34:16.678261Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:34:16.893468Z","iopub.execute_input":"2025-02-15T09:34:16.893672Z","iopub.status.idle":"2025-02-15T09:34:16.900755Z","shell.execute_reply.started":"2025-02-15T09:34:16.893655Z","shell.execute_reply":"2025-02-15T09:34:16.900155Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['file']=\"/kaggle/input/applications-of-deep-learning-wustl-fall-2023/\"+df['file']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:34:17.322244Z","iopub.execute_input":"2025-02-15T09:34:17.322482Z","iopub.status.idle":"2025-02-15T09:34:17.330106Z","shell.execute_reply.started":"2025-02-15T09:34:17.322462Z","shell.execute_reply":"2025-02-15T09:34:17.329511Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:34:20.114786Z","iopub.execute_input":"2025-02-15T09:34:20.115058Z","iopub.status.idle":"2025-02-15T09:34:20.122750Z","shell.execute_reply.started":"2025-02-15T09:34:20.115035Z","shell.execute_reply":"2025-02-15T09:34:20.121967Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:35:28.678701Z","iopub.execute_input":"2025-02-15T09:35:28.678984Z","iopub.status.idle":"2025-02-15T09:35:28.683792Z","shell.execute_reply.started":"2025-02-15T09:35:28.678963Z","shell.execute_reply":"2025-02-15T09:35:28.683054Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['glasses'].value_counts()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:34:36.657834Z","iopub.execute_input":"2025-02-15T09:34:36.658161Z","iopub.status.idle":"2025-02-15T09:34:36.669458Z","shell.execute_reply.started":"2025-02-15T09:34:36.658109Z","shell.execute_reply":"2025-02-15T09:34:36.668820Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(15, 5))\nlabels=[0,1]\nfor i, label in enumerate(labels):\n    sample_img_path = df[df['glasses'] == label].iloc[0]['file'] \n    img = cv2.imread(sample_img_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) \n    \n    plt.subplot(1, 5, i + 1)\n    plt.imshow(img)\n    plt.axis('off')\n    plt.title(label)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:35:17.041856Z","iopub.execute_input":"2025-02-15T09:35:17.042221Z","iopub.status.idle":"2025-02-15T09:35:17.423183Z","shell.execute_reply.started":"2025-02-15T09:35:17.042111Z","shell.execute_reply":"2025-02-15T09:35:17.422292Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(23,8))\nax=sns.countplot(x=df[\"glasses\"],palette=\"viridis\",order=df['glasses'].value_counts().index)\nfor p in ax.containers:\n    ax.bar_label(p, fontsize=12, color='black', padding=5);","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:35:46.049664Z","iopub.execute_input":"2025-02-15T09:35:46.049977Z","iopub.status.idle":"2025-02-15T09:35:46.234993Z","shell.execute_reply.started":"2025-02-15T09:35:46.049953Z","shell.execute_reply":"2025-02-15T09:35:46.234228Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Preprocess Images","metadata":{}},{"cell_type":"code","source":"x=[]\nfor img in df[\"file\"]:\n    img=cv2.imread(img)\n    img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n    img=cv2.resize(img,(64,64))\n    img=img/255.0\n    x.append(img)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:36:16.475044Z","iopub.execute_input":"2025-02-15T09:36:16.475381Z","iopub.status.idle":"2025-02-15T09:38:19.628844Z","shell.execute_reply.started":"2025-02-15T09:36:16.475355Z","shell.execute_reply":"2025-02-15T09:38:19.627815Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x=np.array(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:38:19.629964Z","iopub.execute_input":"2025-02-15T09:38:19.630290Z","iopub.status.idle":"2025-02-15T09:38:20.359886Z","shell.execute_reply.started":"2025-02-15T09:38:19.630261Z","shell.execute_reply":"2025-02-15T09:38:20.359213Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y=df[[\"glasses\"]]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:38:59.883336Z","iopub.execute_input":"2025-02-15T09:38:59.883648Z","iopub.status.idle":"2025-02-15T09:38:59.888322Z","shell.execute_reply.started":"2025-02-15T09:38:59.883625Z","shell.execute_reply":"2025-02-15T09:38:59.887491Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x.shape,y.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T09:39:00.209520Z","iopub.execute_input":"2025-02-15T09:39:00.209807Z","iopub.status.idle":"2025-02-15T09:39:00.215111Z","shell.execute_reply.started":"2025-02-15T09:39:00.209783Z","shell.execute_reply":"2025-02-15T09:39:00.214294Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Modelling","metadata":{}},{"cell_type":"code","source":"x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=.2,random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:22:02.164815Z","iopub.execute_input":"2025-02-15T10:22:02.165160Z","iopub.status.idle":"2025-02-15T10:22:02.868459Z","shell.execute_reply.started":"2025-02-15T10:22:02.165104Z","shell.execute_reply":"2025-02-15T10:22:02.867497Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model=Sequential()\nmodel.add(Input(shape=(64,64,3)))\nmodel.add(Conv2D(64,kernel_size=(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(128,kernel_size=(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(256,kernel_size=(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(512,kernel_size=(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(1024,kernel_size=(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\n\n\nmodel.add(Flatten())\n\nmodel.add(Dense(1024,activation='relu'))\nmodel.add(Dense(512,activation='relu'))\nmodel.add(Dense(256,activation='relu'))\nmodel.add(Dense(128,activation='relu'))\n\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2,activation='softmax'))\n\nmodel.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:06:02.529724Z","iopub.execute_input":"2025-02-15T10:06:02.529941Z","iopub.status.idle":"2025-02-15T10:06:02.823712Z","shell.execute_reply.started":"2025-02-15T10:06:02.529922Z","shell.execute_reply":"2025-02-15T10:06:02.822849Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history=model.fit(x_train,y_train,validation_data=(x_test,y_test),epochs=50,batch_size=36,verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:06:04.488328Z","iopub.execute_input":"2025-02-15T10:06:04.488621Z","iopub.status.idle":"2025-02-15T10:18:11.751104Z","shell.execute_reply.started":"2025-02-15T10:06:04.488599Z","shell.execute_reply":"2025-02-15T10:18:11.750168Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('cnn_model.h5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:18:11.752611Z","iopub.execute_input":"2025-02-15T10:18:11.752918Z","iopub.status.idle":"2025-02-15T10:18:12.127267Z","shell.execute_reply.started":"2025-02-15T10:18:11.752893Z","shell.execute_reply":"2025-02-15T10:18:12.126391Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Model Analysis","metadata":{}},{"cell_type":"code","source":"predictions=model.predict(x_test)\npredictions=predictions.argmax(axis=-1)\npredictions=np.array(predictions)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:22:04.910878Z","iopub.execute_input":"2025-02-15T10:22:04.911190Z","iopub.status.idle":"2025-02-15T10:22:06.482362Z","shell.execute_reply.started":"2025-02-15T10:22:04.911158Z","shell.execute_reply":"2025-02-15T10:22:06.481493Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"accuracy_score(predictions,y_test)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:22:06.483510Z","iopub.execute_input":"2025-02-15T10:22:06.483840Z","iopub.status.idle":"2025-02-15T10:22:06.492344Z","shell.execute_reply.started":"2025-02-15T10:22:06.483806Z","shell.execute_reply":"2025-02-15T10:22:06.491542Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cm = confusion_matrix(y_test, predictions)  \nlabel_encoding_dict = {'No Glass':0,'Glass':1}\n\nplt.figure(figsize=(5, 5))\nsns.heatmap(\n    cm,\n    annot=True,\n    fmt='g',\n    cmap='Blues',\n    xticklabels=label_encoding_dict.keys(),\n    yticklabels=label_encoding_dict.keys(),\n    cbar=False\n)\nplt.xlabel('Predicted Labels')\nplt.ylabel('Actual Labels')\nplt.title('Confusion Matrix');","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:18:26.846879Z","iopub.execute_input":"2025-02-15T10:18:26.847198Z","iopub.status.idle":"2025-02-15T10:18:26.956292Z","shell.execute_reply.started":"2025-02-15T10:18:26.847171Z","shell.execute_reply":"2025-02-15T10:18:26.955603Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label_decoding_dict = {0: 'No Glass', 1: 'Glass'}\n\ny_test = np.array(y_test)\n\ny_test_names = [label_decoding_dict[label.item()] for label in y_test]\npredictions_names = [label_decoding_dict[label.item()] for label in predictions]\n\nplt.figure(figsize=(15, 5))\n\nnum_samples = 10\nindices = np.random.choice(len(x_test), num_samples, replace=False)\n\nfor i, idx in enumerate(indices):\n    plt.subplot(2, 5, i + 1)\n    plt.imshow(x_test[idx])  \n    plt.axis('off')\n    plt.title(f\"Actual: {y_test_names[idx]}\\nPredicted: {predictions_names[idx]}\")\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:18:27.846174Z","iopub.execute_input":"2025-02-15T10:18:27.846512Z","iopub.status.idle":"2025-02-15T10:18:28.576069Z","shell.execute_reply.started":"2025-02-15T10:18:27.846490Z","shell.execute_reply":"2025-02-15T10:18:28.575101Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history.history['accuracy'][-1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:18:30.477005Z","iopub.execute_input":"2025-02-15T10:18:30.477317Z","iopub.status.idle":"2025-02-15T10:18:30.482347Z","shell.execute_reply.started":"2025-02-15T10:18:30.477292Z","shell.execute_reply":"2025-02-15T10:18:30.481657Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history.history['accuracy'],label='Accuracy')\nplt.plot(history.history['val_accuracy'],label='Val_Accuracy')\nplt.legend();","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:18:37.162019Z","iopub.execute_input":"2025-02-15T10:18:37.162347Z","iopub.status.idle":"2025-02-15T10:18:37.338835Z","shell.execute_reply.started":"2025-02-15T10:18:37.162322Z","shell.execute_reply":"2025-02-15T10:18:37.338155Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Testing the Model","metadata":{}},{"cell_type":"code","source":"df_test=pd.read_csv('/kaggle/input/applications-of-deep-learning-wustl-fall-2023/test.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:18:39.367047Z","iopub.execute_input":"2025-02-15T10:18:39.367392Z","iopub.status.idle":"2025-02-15T10:18:39.377276Z","shell.execute_reply.started":"2025-02-15T10:18:39.367366Z","shell.execute_reply":"2025-02-15T10:18:39.376549Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:18:39.651721Z","iopub.execute_input":"2025-02-15T10:18:39.651931Z","iopub.status.idle":"2025-02-15T10:18:39.658961Z","shell.execute_reply.started":"2025-02-15T10:18:39.651913Z","shell.execute_reply":"2025-02-15T10:18:39.658208Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test['file']=\"/kaggle/input/applications-of-deep-learning-wustl-fall-2023/\"+df_test['file']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:18:41.138074Z","iopub.execute_input":"2025-02-15T10:18:41.138428Z","iopub.status.idle":"2025-02-15T10:18:41.143825Z","shell.execute_reply.started":"2025-02-15T10:18:41.138403Z","shell.execute_reply":"2025-02-15T10:18:41.142909Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_test=[]\nfor img in df_test[\"file\"]:\n    img=cv2.imread(img)\n    img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n    img=cv2.resize(img,(64,64))\n    img=img/255.0\n    x_test.append(img)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:18:41.405697Z","iopub.execute_input":"2025-02-15T10:18:41.405927Z","iopub.status.idle":"2025-02-15T10:19:02.508524Z","shell.execute_reply.started":"2025-02-15T10:18:41.405908Z","shell.execute_reply":"2025-02-15T10:19:02.507574Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_test=np.array(x_test)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:19:02.509740Z","iopub.execute_input":"2025-02-15T10:19:02.510041Z","iopub.status.idle":"2025-02-15T10:19:02.714372Z","shell.execute_reply.started":"2025-02-15T10:19:02.510012Z","shell.execute_reply":"2025-02-15T10:19:02.713616Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions=model.predict(x_test)\npredictions=predictions.argmax(axis=-1)\npredictions=np.array(predictions)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:19:02.716019Z","iopub.execute_input":"2025-02-15T10:19:02.716359Z","iopub.status.idle":"2025-02-15T10:19:05.020860Z","shell.execute_reply.started":"2025-02-15T10:19:02.716330Z","shell.execute_reply":"2025-02-15T10:19:05.020190Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission=pd.DataFrame({\n    'id':df_test['id'],\n    'glasses':predictions\n})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:19:05.021800Z","iopub.execute_input":"2025-02-15T10:19:05.022017Z","iopub.status.idle":"2025-02-15T10:19:05.026052Z","shell.execute_reply.started":"2025-02-15T10:19:05.021999Z","shell.execute_reply":"2025-02-15T10:19:05.025221Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.to_csv('submission.csv',index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T10:19:05.026810Z","iopub.execute_input":"2025-02-15T10:19:05.027046Z","iopub.status.idle":"2025-02-15T10:19:05.045354Z","shell.execute_reply.started":"2025-02-15T10:19:05.027027Z","shell.execute_reply":"2025-02-15T10:19:05.044717Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Conclusion\n\nThe model achieved an impressive accuracy of **99.82%**, demonstrating its ability to effectively detect glass in images. This high accuracy indicates that the model performs well in distinguishing between images containing glass and those that do not. ","metadata":{}}]}