-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject_detection.py
More file actions
282 lines (205 loc) · 9.23 KB
/
object_detection.py
File metadata and controls
282 lines (205 loc) · 9.23 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
277
278
279
280
281
import cv2
import os
import numpy as np
from .utils import download_file
initialize = True
net = None
dest_dir = os.path.expanduser('~') + os.path.sep + '.cvlib' + os.path.sep + 'object_detection' + os.path.sep + 'yolo' + os.path.sep + 'yolov3'
classes = None
COLORS = np.random.uniform(0, 255, size=(80, 3))
def populate_class_labels():
class_file_name = 'yolov3_classes.txt'
class_file_abs_path = dest_dir + os.path.sep + class_file_name
url = 'https://github.com/arunponnusamy/object-detection-opencv/raw/master/yolov3.txt'
if not os.path.exists(class_file_abs_path):
download_file(url=url, file_name=class_file_name, dest_dir=dest_dir)
f = open(class_file_abs_path, 'r')
classes = [line.strip() for line in f.readlines()]
return classes
def get_output_layers(net):
layer_names = net.getLayerNames()
output_layers = [layer_names[i- 1] for i in net.getUnconnectedOutLayers()]
return output_layers
def draw_bbox(img, bbox, labels, confidence, colors=None, write_conf=False):
"""A method to apply a box to the image
Args:
img: An image in the form of a numPy array
bbox: An array of bounding boxes
labels: An array of labels
colors: An array of colours the length of the number of targets(80)
write_conf: An option to write the confidences to the image
"""
global COLORS
global classes
if classes is None:
classes = populate_class_labels()
for i, label in enumerate(labels):
if write_conf:
label += ' ' + str(format(confidence[i] * 100, '.2f')) + '%'
##New Stuff
labels_hold = labels
for label_hold in labels_hold:
for letter in label_hold:
if letter.isdigit():
label_hold = label_hold.replace(letter,"")
##
## This should really go above 'if write_conf'
if colors is None:
color = COLORS[classes.index(label_hold)]
else:
color = colors[classes.index(label_hold)]
##
cv2.rectangle(img, (bbox[i][0],bbox[i][1]), (bbox[i][2],bbox[i][3]), color, 2)
cv2.putText(img, label, (bbox[i][0],bbox[i][1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
return img
def detect_common_objects(image, confidence=0.5, nms_thresh=0.3, model='yolov4', enable_gpu=False):
"""A method to detect common objects
Args:
image: A colour image in a numpy array
confidence: A value to filter out objects recognised to a lower confidence score
nms_thresh: An NMS value
model: The detection model to be used, supported models are: yolov3, yolov3-tiny, yolov4, yolov4-tiny
enable_gpu: A boolean to set whether the GPU will be used
"""
Height, Width = image.shape[:2]
scale = 0.00392
global classes
global dest_dir
if model == 'yolov3-tiny':
config_file_name = 'yolov3-tiny.cfg'
cfg_url = "https://github.com/pjreddie/darknet/raw/master/cfg/yolov3-tiny.cfg"
weights_file_name = 'yolov3-tiny.weights'
weights_url = 'https://pjreddie.com/media/files/yolov3-tiny.weights'
blob = cv2.dnn.blobFromImage(image, scale, (416,416), (0,0,0), True, crop=False)
elif model == 'yolov4':
config_file_name = 'yolov4.cfg'
cfg_url = 'https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/yolov4.cfg'
weights_file_name = 'yolov4.weights'
weights_url = 'https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov4.weights'
blob = cv2.dnn.blobFromImage(image, scale, (416,416), (0,0,0), True, crop=False)
elif model == 'yolov4-tiny':
config_file_name = 'yolov4-tiny.cfg'
cfg_url = 'https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/yolov4-tiny.cfg'
weights_file_name = 'yolov4-tiny.weights'
weights_url = 'https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v4_pre/yolov4-tiny.weights'
blob = cv2.dnn.blobFromImage(image, scale, (416,416), (0,0,0), True, crop=False)
else:
config_file_name = 'yolov3.cfg'
cfg_url = 'https://github.com/arunponnusamy/object-detection-opencv/raw/master/yolov3.cfg'
weights_file_name = 'yolov3.weights'
weights_url = 'https://pjreddie.com/media/files/yolov3.weights'
blob = cv2.dnn.blobFromImage(image, scale, (416,416), (0,0,0), True, crop=False)
config_file_abs_path = dest_dir + os.path.sep + config_file_name
weights_file_abs_path = dest_dir + os.path.sep + weights_file_name
if not os.path.exists(config_file_abs_path):
download_file(url=cfg_url, file_name=config_file_name, dest_dir=dest_dir)
if not os.path.exists(weights_file_abs_path):
download_file(url=weights_url, file_name=weights_file_name, dest_dir=dest_dir)
global initialize
global net
if initialize:
classes = populate_class_labels()
net = cv2.dnn.readNet(weights_file_abs_path, config_file_abs_path)
initialize = False
# enables opencv dnn module to use CUDA on Nvidia card instead of cpu
if enable_gpu:
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
net.setInput(blob)
outs = net.forward(get_output_layers(net))
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
max_conf = scores[class_id]
if max_conf > confidence:
center_x = int(detection[0] * Width)
center_y = int(detection[1] * Height)
w = int(detection[2] * Width)
h = int(detection[3] * Height)
x = center_x - (w / 2)
y = center_y - (h / 2)
class_ids.append(class_id)
confidences.append(float(max_conf))
boxes.append([x, y, w, h])
indices = cv2.dnn.NMSBoxes(boxes, confidences, confidence, nms_thresh)
bbox = []
label = []
conf = []
for i in indices:
box = boxes[i]
x = box[0]
y = box[1]
w = box[2]
h = box[3]
bbox.append([int(x), int(y), int(x+w), int(y+h)])
label.append(str(classes[class_ids[i]]))
conf.append(confidences[i])
return bbox, label, conf
class YOLO:
def __init__(self, weights, config, labels, version='yolov3'):
print('[INFO] Initializing YOLO ..')
self.config = config
self.weights = weights
self.version = version
with open(labels, 'r') as f:
self.labels = [line.strip() for line in f.readlines()]
self.colors = np.random.uniform(0, 255, size=(len(self.labels), 3))
self.net = cv2.dnn.readNet(self.weights, self.config)
layer_names = self.net.getLayerNames()
self.output_layers = [layer_names[i - 1] for i in self.net.getUnconnectedOutLayers()]
def detect_objects(self, image, confidence=0.5, nms_thresh=0.3,
enable_gpu=False):
if enable_gpu:
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
Height, Width = image.shape[:2]
scale = 0.00392
blob = cv2.dnn.blobFromImage(image, scale, (416,416), (0,0,0), True,
crop=False)
self.net.setInput(blob)
outs = self.net.forward(self.output_layers)
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
max_conf = scores[class_id]
if max_conf > confidence:
center_x = int(detection[0] * Width)
center_y = int(detection[1] * Height)
w = int(detection[2] * Width)
h = int(detection[3] * Height)
x = center_x - (w / 2)
y = center_y - (h / 2)
class_ids.append(class_id)
confidences.append(float(max_conf))
boxes.append([x, y, w, h])
indices = cv2.dnn.NMSBoxes(boxes, confidences, confidence, nms_thresh)
bbox = []
label = []
conf = []
for i in indices:
box = boxes[i]
x = box[0]
y = box[1]
w = box[2]
h = box[3]
bbox.append([int(x), int(y), int(x+w), int(y+h)])
label.append(str(self.labels[class_ids[i]]))
conf.append(confidences[i])
return bbox, label, conf
def draw_bbox(self, img, bbox, labels, confidence, colors=None, write_conf=False):
if colors is None:
colors = self.colors
for i, label in enumerate(labels):
color = colors[self.labels.index(label)]
if write_conf:
label += ' ' + str(format(confidence[i] * 100, '.2f')) + '%'
cv2.rectangle(img, (bbox[i][0],bbox[i][1]), (bbox[i][2],bbox[i][3]), color, 2)
cv2.putText(img, label, (bbox[i][0],bbox[i][1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)