-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImageScanner.py
159 lines (123 loc) · 4.53 KB
/
ImageScanner.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
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
from ultralytics import YOLO
import logging
import cv2
from ultralytics.yolo.utils.plotting import Annotator
import torch.nn as nn
import torch
from torch import Tensor
from typing import Type
import torchvision
from torchvision import transforms, models
import math
from PIL import Image
import numpy as np
from scipy.optimize import linear_sum_assignment
from collections import defaultdict
# Disables console logs to improve speed
logging.disable(logging.INFO)
colors = ['beige', 'black', 'blue', 'brown', 'gold', 'green', 'grey', 'orange', 'pink', 'purple', 'red', 'silver', 'tan', 'white', 'yellow']
color_transformer = transforms.Compose([
transforms.Resize((64, 64)),
transforms.ToTensor()
])
class NET(nn.Module):
def __init__(self):
super(NET, self).__init__()
# first layer
self.conv1 = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(32),
nn.Conv2d(32, 32, 3, stride=2, padding=1),
nn.ReLU(),
nn.BatchNorm2d(32),
nn.MaxPool2d(2, 2),
nn.Dropout(0.25)
)
# Second layer
self.conv2 = nn.Sequential(
nn.Conv2d(32, 64, 3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(64),
nn.Conv2d(64, 64, 3, stride=2, padding=1),
nn.ReLU(),
nn.BatchNorm2d(64),
nn.MaxPool2d(2, 2),
nn.Dropout(0.25)
)
# Third layer
self.conv3 = nn.Sequential(
nn.Conv2d(64, 128, 3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(128),
nn.MaxPool2d(2, 2),
nn.Dropout(0.25)
)
self.fc = nn.Sequential(
nn.Linear(512, int(len(colors)))
)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = x.view(x.size(0), -1)
return self.fc(x)
color_classifier = NET()
color_classifier.load_state_dict(torch.load("C:/Users/benjamin.guerrieri/Documents/AutoSenseBackup/Models/color_model.pt"))
# Identifies classes to be searched for that the model was trained on
classes = ['Convertible', 'Coupe', 'Minivan', 'SUV', 'Sedan', 'Truck', 'Van']
# Declares a transformer to make all images fit the input size of the trained model
transformer = torchvision.transforms.Compose([
transforms.Resize(size=(int(224), int(224))),
transforms.ToTensor(),
])
# Transfer Learning Model
classifier = models.resnet34()
num_ftrs = classifier.fc.in_features
classifier.fc = nn.Linear(num_ftrs, len(classes))
# Loads the model that is trained on our data
classifier.load_state_dict(torch.load("C:/Users/benjamin.guerrieri/Documents/AutoSenseBackup/Models/car_model_TL.pt"))
def get_probs(output):
probs = nn.functional.softmax(output, dim=1)
probs = probs.tolist()
p = max(probs[0])
p = p * 100
return str(format(p, '.1f'))
def predict(img):
classifier.eval()
color_classifier.eval()
color_img = color_transformer(img).float()
img_normalized = transformer(img).float()
img_normalized = img_normalized[np.newaxis, ...]
color_img = color_img[np.newaxis, ...]
output = classifier(img_normalized)
color_output = color_classifier(color_img)
prob = get_probs(output)
output = torch.argmax(output, 1)
color_output = torch.argmax(color_output, 1)
return str(colors[color_output]).title() + " " + str(classes[output]) + " " + prob + "%"
WINDOW_NAME = "Video Classifier"
model = YOLO('./YOLOModels/yolov8n.pt')
path = r'C:\Users\benjamin.guerrieri\Documents\AutoSenseBackup\SingleTestImages\NotCropped\5cars.jpg'
img = cv2.imread(path)
# cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_FREERATIO)
# cv2.setWindowProperty(WINDOW_NAME, cv2.WINDOW_AUTOSIZE, cv2.WINDOW_FREERATIO)
# cv2.imshow(WINDOW_NAME, img)
frame = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
results = model.predict(frame)
for r in results:
annotator = Annotator(img)
boxes = r.boxes
for j, box in enumerate(boxes):
b = box.xyxy[0].tolist() # get box coordinates in (top, left, bottom, right) format
class_id = r.names[box.cls[0].item()]
if str(class_id) == "car" or str(class_id) == "bus" or str(class_id) == "truck":
im_pil = Image.fromarray(frame)
im_pil = im_pil.crop([round(x) for x in b])
corner = [round(b[0]), round(b[1])]
c = predict(im_pil)
annotator.box_label(b, c)
img = annotator.result()
cv2.imshow(WINDOW_NAME, img)
cv2.waitKey(0)
cv2.destroyAllWindows()