-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathai_sorter.py
59 lines (45 loc) · 1.5 KB
/
ai_sorter.py
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
# use model of accuracy 93% to predict the class of the garbage in camera
import cv2
import numpy as np
import torchvision.transforms as transforms
import torch
# load the model
model = torch.load('garbage_classification-01.pth', map_location=torch.device('cpu'))
model.eval()
# load the labels
class_names = ['e-waste', 'glass', 'metal', 'paper', 'plastic']
# define the transforms
transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
# use the camera
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
continue
# convert the frame to RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# convert the frame to tensor
inputs = transform(frame)
inputs = inputs.unsqueeze(0)
# get the prediction
outputs = model(inputs)
_, predicted = torch.max(outputs, 1)
# get the class name
class_name = class_names[predicted]
if class_name != 'background': # Add this condition to check if something is detected
# put the class name on the frame
cv2.putText(frame, class_name, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 3, (0, 0, 255), 3, cv2.LINE_AA)
# convert the frame back to BGR
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
# display the frame
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
print('Camera closed')