-
Notifications
You must be signed in to change notification settings - Fork 1
/
np_detection.py
56 lines (43 loc) · 1.8 KB
/
np_detection.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
import cv2
import numpy as np
import matplotlib.pyplot as plt
model = cv2.dnn.readNet('yolov3_np_last.weights','yolov3_np.cfg')
claases = []
with open('vehicle.names', 'r') as f:
claases = [line.strip() for line in f.readlines()]
layers = model.getLayerNames()
outputLayers = [layers[i[0] - 1] for i in model.getUnconnectedOutLayers()]
test_img = cv2.imread('test2.jpeg')
#test_img = cv2.resize(test_img, None, fx=0.8, fy=0.8)
height, width, _ = test_img.shape
features = cv2.dnn.blobFromImage(test_img, 0.00392, (608, 608), (0,0,0), True, crop=False)
model.setInput(features)
output = model.forward(outputLayers)
boxes = []
confidences = []
class_ids = []
for o in output:
for detection in o:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
centerX = int(detection[0] * width)
centerY = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x, y = int(centerX - w / 2), int(centerY - h / 2)
boxes.append([x,y,w,h]) # pass coordinates
class_ids.append(class_id) # pass corresponding class
confidences.append(float(confidence)) # pass corresponding confidence class
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
for i in range(len(boxes)):
if i in indices:
x,y,w,h = boxes[i]
label = claases[class_ids[i]]
confidence = round(confidences[i] * 100, 2)
cv2.rectangle(test_img, (x,y), (x + w, y + h), (0,0,255), 3)
cv2.putText(test_img, label + ' ' + str(confidence) + '%', (x, y - 8), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 1, cv2.LINE_AA)
cv2.imshow('Vehicle detection', test_img)
cv2.waitKey(0)
cv2.destroyAllWindows()