-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwaste_classification.py
More file actions
276 lines (206 loc) · 8.05 KB
/
waste_classification.py
File metadata and controls
276 lines (206 loc) · 8.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# -*- coding: utf-8 -*-
"""Waste classification.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1He-SjfOmrPOdw7HiyFGKwzcZhWiBbAgx
####**Waste** **Classification** **using** **CNN**
***Introduction***
* Waste is a significant global issue. Increasing volumes of waste are being generated as the global population and living standards rise. People are increasingly concerned about the production of waste and its effect, and are seeking ways to deal with the problem.
* Recycling is the process of converting waste materials into new materials and objects. The recovery of energy from waste materials is often included in this concept. The recyclability of a material depends on its ability to reacquire the properties it had in its original state. It is an alternative to "conventional" waste disposal that can save material and help lower greenhouse gas emissions. Recycling can prevent the waste of potentially useful materials and reduce the consumption of fresh raw materials, thereby reducing: energy usage, air pollution (from incineration), and water pollution (from landfilling)
🟢 In this notebook, we will classify waste as organic or recyclable using Convolutional Neural Network (CNN).
"""
from google.colab import drive
drive.mount('/content/drive')
# Paths to training and testing datasets in Drive
train_path = "/content/drive/MyDrive/DATASET/TRAIN/"
test_path = "/content/drive/MyDrive/DATASET/TEST/"
import os
import matplotlib.pyplot as plt
import cv2
# Path to your training dataset
train_path = '/content/drive/MyDrive/DATASET/TRAIN/'
# Classes
classes = ['O', 'R']
for cls in classes:
class_path = os.path.join(train_path, cls)
if os.path.exists(class_path):
print(f"\nClass: {cls}")
images = os.listdir(class_path)
# Display all images one by one
for img_name in images:
img_path = os.path.join(class_path, img_name)
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img)
plt.title(f"Class: {cls} | File: {img_name}")
plt.axis("off")
plt.show()
else:
print(f"Class {cls} folder not found!")
"""#####Import Libraries
"""
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Activation, Dropout, Flatten, Dense, BatchNormalization
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.utils import plot_model
from tensorflow.keras.utils import img_to_array, load_img # now comes from utils
from glob import glob
"""###Visualization"""
from collections import Counter
import pandas as pd
import matplotlib.pyplot as plt
label_counts = Counter(y_data)
df_counts = pd.DataFrame.from_dict(label_counts, orient='index', columns=['count']).reset_index()
df_counts.rename(columns={'index': 'label'}, inplace=True)
plt.figure(figsize=(8,5))
bars = plt.bar(df_counts['label'], df_counts['count'], color='skyblue', edgecolor='black')
plt.title("Class Distribution in Dataset", fontsize=14)
plt.xlabel("Class Labels", fontsize=12)
plt.ylabel("Number of Images", fontsize=12)
plt.xticks(rotation=45)
# Add counts on top of bars
for bar, count in zip(bars, df_counts['count']):
plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 5,
str(count), ha='center', va='bottom')
plt.show()
print("x_data shape:", x_data.shape) # e.g. (num_images, 128, 128, 3)
print("y_data shape:", y_data.shape) # e.g. (num_images,)
from collections import Counter
Counter(y_data)
import matplotlib.pyplot as plt
from collections import Counter
# Example dataset labels
y_data = ['Organic', 'Recyclable', 'Organic', 'Organic', 'Recyclable', 'Organic']
# Custom colors (green for Organic, pink for Recyclable)
colors = ['#a0d157', '#c48bb8']
# Count labels
label_counts = Counter(y_data)
# Pie chart
plt.figure(figsize=(6,6))
plt.pie(
label_counts.values(),
startangle=90,
explode=[0.05]*len(label_counts), # explode all slices slightly
autopct='%0.2f%%', # show percentages with 2 decimals
labels=label_counts.keys(),
colors=colors[:len(label_counts)], # assign colors dynamically
radius=1.2
)
plt.title("Class Distribution in Dataset", fontsize=14)
plt.show()
print(set(y_data))
import os
train_path = "/content/drive/MyDrive/DATASET/TRAIN/"
# Show classes
classes = os.listdir(train_path)
print("Classes found:", classes)
# Show file counts per class
for cls in classes:
folder = os.path.join(train_path, cls)
files = os.listdir(folder)
print(f"Class: {cls}, Files: {len(files)}")
print("Sample files:", files[:5]) # show first 5
className = glob(train_path + '/*' )
numberOfClass = len(className)
print("Number Of Class: ",numberOfClass)
"""######Convolutional Neural Network - CNN"""
model = Sequential()
model.add(Conv2D(32,(3,3),input_shape=(224,224,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D())
model.add(Conv2D(64,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D())
model.add(Conv2D(128,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(256))
model.add(Activation("relu"))
model.add(Dropout(0.5))
model.add(Dense(64))
model.add(Activation("relu"))
model.add(Dropout(0.5))
model.add(Dense(numberOfClass, activation="softmax")) # ✅ Softmax
model.compile(loss="categorical_crossentropy", # ✅
optimizer="adam",
metrics=["accuracy"])
batch_size = 32 # ✅ safer value
plot_model(model)
train_datagen = ImageDataGenerator(rescale= 1./255)
test_datagen = ImageDataGenerator(rescale= 1./255)
train_generator = train_datagen.flow_from_directory(
train_path,
target_size= (224,224),
batch_size = batch_size,
color_mode= "rgb",
class_mode= "categorical")
test_generator = test_datagen.flow_from_directory(
test_path,
target_size= (224,224),
batch_size = batch_size,
color_mode= "rgb",
class_mode= "categorical")
hist = model.fit(
train_generator,
epochs=10,
validation_data=test_generator)
plt.figure(figsize=[10,6])
plt.plot(hist.history["accuracy"], label="Train Accuracy")
plt.plot(hist.history["val_accuracy"], label="Validation Accuracy")
plt.title("Training vs Validation Accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.grid(True)
plt.show()
plt.figure(figsize=(10,6))
plt.plot(hist.history['loss'], label = "Train loss")
plt.plot(hist.history['val_loss'], label = "Validation loss")
plt.legend()
plt.show()
"""##Model **Prediction**
"""
import cv2
import matplotlib.pyplot as plt
import numpy as np
def predict_func(img):
# Show the input image
plt.figure(figsize=(6,4))
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.tight_layout()
plt.show()
# Preprocess for model
img_resized = cv2.resize(img, (224, 224))
img_resized = np.reshape(img_resized, [1, 224, 224, 3]) # batch size = 1
# Prediction
result = np.argmax(model.predict(img_resized))
# Output class
if result == 0:
print("\033[94m" + "This image -> Recyclable" + "\033[0m")
elif result == 1:
print("\033[94m" + "This image -> Organic" + "\033[0m")
else:
print("\033[91m" + "Unknown class" + "\033[0m")
# Load test image from Google Drive
test_img = cv2.imread("/content/drive/MyDrive/DATASET/TEST/O/O_12573.jpg")
if test_img is None:
print("Error: Image not found. Please check the path.")
else:
predict_func(test_img)
import cv2
# Now your code works
test_img = cv2.imread("/content/drive/MyDrive/DATASET/TEST/O/O_13487.jpg")
if test_img is None:
print("Error: Image not found. Please check the path.")
else:
predict_func(test_img)
def predict_func(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.resize(img, (224, 224))
img = np.expand_dims(img, axis=0) / 255.0
return model.predict(img)
# Now call it
test_img = cv2.imread("/content/drive/MyDrive/DATASET/TEST/R/R_10753.jpg")
print(predict_func(test_img))