Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/dnn/object_detection.py
16337 views
1
import cv2 as cv
2
import argparse
3
import numpy as np
4
5
from common import *
6
from tf_text_graph_common import readTextMessage
7
from tf_text_graph_ssd import createSSDGraph
8
from tf_text_graph_faster_rcnn import createFasterRCNNGraph
9
10
backends = (cv.dnn.DNN_BACKEND_DEFAULT, cv.dnn.DNN_BACKEND_HALIDE, cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_BACKEND_OPENCV)
11
targets = (cv.dnn.DNN_TARGET_CPU, cv.dnn.DNN_TARGET_OPENCL, cv.dnn.DNN_TARGET_OPENCL_FP16, cv.dnn.DNN_TARGET_MYRIAD)
12
13
parser = argparse.ArgumentParser(add_help=False)
14
parser.add_argument('--zoo', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models.yml'),
15
help='An optional path to file with preprocessing parameters.')
16
parser.add_argument('--input', help='Path to input image or video file. Skip this argument to capture frames from a camera.')
17
parser.add_argument('--out_tf_graph', default='graph.pbtxt',
18
help='For models from TensorFlow Object Detection API, you may '
19
'pass a .config file which was used for training through --config '
20
'argument. This way an additional .pbtxt file with TensorFlow graph will be created.')
21
parser.add_argument('--framework', choices=['caffe', 'tensorflow', 'torch', 'darknet', 'dldt'],
22
help='Optional name of an origin framework of the model. '
23
'Detect it automatically if it does not set.')
24
parser.add_argument('--thr', type=float, default=0.5, help='Confidence threshold')
25
parser.add_argument('--nms', type=float, default=0.4, help='Non-maximum suppression threshold')
26
parser.add_argument('--backend', choices=backends, default=cv.dnn.DNN_BACKEND_DEFAULT, type=int,
27
help="Choose one of computation backends: "
28
"%d: automatically (by default), "
29
"%d: Halide language (http://halide-lang.org/), "
30
"%d: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
31
"%d: OpenCV implementation" % backends)
32
parser.add_argument('--target', choices=targets, default=cv.dnn.DNN_TARGET_CPU, type=int,
33
help='Choose one of target computation devices: '
34
'%d: CPU target (by default), '
35
'%d: OpenCL, '
36
'%d: OpenCL fp16 (half-float precision), '
37
'%d: VPU' % targets)
38
args, _ = parser.parse_known_args()
39
add_preproc_args(args.zoo, parser, 'object_detection')
40
parser = argparse.ArgumentParser(parents=[parser],
41
description='Use this script to run object detection deep learning networks using OpenCV.',
42
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
43
args = parser.parse_args()
44
45
args.model = findFile(args.model)
46
args.config = findFile(args.config)
47
args.classes = findFile(args.classes)
48
49
# If config specified, try to load it as TensorFlow Object Detection API's pipeline.
50
config = readTextMessage(args.config)
51
if 'model' in config:
52
print('TensorFlow Object Detection API config detected')
53
if 'ssd' in config['model'][0]:
54
print('Preparing text graph representation for SSD model: ' + args.out_tf_graph)
55
createSSDGraph(args.model, args.config, args.out_tf_graph)
56
args.config = args.out_tf_graph
57
elif 'faster_rcnn' in config['model'][0]:
58
print('Preparing text graph representation for Faster-RCNN model: ' + args.out_tf_graph)
59
createFasterRCNNGraph(args.model, args.config, args.out_tf_graph)
60
args.config = args.out_tf_graph
61
62
63
# Load names of classes
64
classes = None
65
if args.classes:
66
with open(args.classes, 'rt') as f:
67
classes = f.read().rstrip('\n').split('\n')
68
69
# Load a network
70
net = cv.dnn.readNet(args.model, args.config, args.framework)
71
net.setPreferableBackend(args.backend)
72
net.setPreferableTarget(args.target)
73
outNames = net.getUnconnectedOutLayersNames()
74
75
confThreshold = args.thr
76
nmsThreshold = args.nms
77
78
def postprocess(frame, outs):
79
frameHeight = frame.shape[0]
80
frameWidth = frame.shape[1]
81
82
def drawPred(classId, conf, left, top, right, bottom):
83
# Draw a bounding box.
84
cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))
85
86
label = '%.2f' % conf
87
88
# Print a label of class.
89
if classes:
90
assert(classId < len(classes))
91
label = '%s: %s' % (classes[classId], label)
92
93
labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
94
top = max(top, labelSize[1])
95
cv.rectangle(frame, (left, top - labelSize[1]), (left + labelSize[0], top + baseLine), (255, 255, 255), cv.FILLED)
96
cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
97
98
layerNames = net.getLayerNames()
99
lastLayerId = net.getLayerId(layerNames[-1])
100
lastLayer = net.getLayer(lastLayerId)
101
102
classIds = []
103
confidences = []
104
boxes = []
105
if net.getLayer(0).outputNameToIndex('im_info') != -1: # Faster-RCNN or R-FCN
106
# Network produces output blob with a shape 1x1xNx7 where N is a number of
107
# detections and an every detection is a vector of values
108
# [batchId, classId, confidence, left, top, right, bottom]
109
for out in outs:
110
for detection in out[0, 0]:
111
confidence = detection[2]
112
if confidence > confThreshold:
113
left = int(detection[3])
114
top = int(detection[4])
115
right = int(detection[5])
116
bottom = int(detection[6])
117
width = right - left + 1
118
height = bottom - top + 1
119
classIds.append(int(detection[1]) - 1) # Skip background label
120
confidences.append(float(confidence))
121
boxes.append([left, top, width, height])
122
elif lastLayer.type == 'DetectionOutput':
123
# Network produces output blob with a shape 1x1xNx7 where N is a number of
124
# detections and an every detection is a vector of values
125
# [batchId, classId, confidence, left, top, right, bottom]
126
for out in outs:
127
for detection in out[0, 0]:
128
confidence = detection[2]
129
if confidence > confThreshold:
130
left = int(detection[3] * frameWidth)
131
top = int(detection[4] * frameHeight)
132
right = int(detection[5] * frameWidth)
133
bottom = int(detection[6] * frameHeight)
134
width = right - left + 1
135
height = bottom - top + 1
136
classIds.append(int(detection[1]) - 1) # Skip background label
137
confidences.append(float(confidence))
138
boxes.append([left, top, width, height])
139
elif lastLayer.type == 'Region':
140
# Network produces output blob with a shape NxC where N is a number of
141
# detected objects and C is a number of classes + 4 where the first 4
142
# numbers are [center_x, center_y, width, height]
143
classIds = []
144
confidences = []
145
boxes = []
146
for out in outs:
147
for detection in out:
148
scores = detection[5:]
149
classId = np.argmax(scores)
150
confidence = scores[classId]
151
if confidence > confThreshold:
152
center_x = int(detection[0] * frameWidth)
153
center_y = int(detection[1] * frameHeight)
154
width = int(detection[2] * frameWidth)
155
height = int(detection[3] * frameHeight)
156
left = int(center_x - width / 2)
157
top = int(center_y - height / 2)
158
classIds.append(classId)
159
confidences.append(float(confidence))
160
boxes.append([left, top, width, height])
161
else:
162
print('Unknown output layer type: ' + lastLayer.type)
163
exit()
164
165
indices = cv.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)
166
for i in indices:
167
i = i[0]
168
box = boxes[i]
169
left = box[0]
170
top = box[1]
171
width = box[2]
172
height = box[3]
173
drawPred(classIds[i], confidences[i], left, top, left + width, top + height)
174
175
# Process inputs
176
winName = 'Deep learning object detection in OpenCV'
177
cv.namedWindow(winName, cv.WINDOW_NORMAL)
178
179
def callback(pos):
180
global confThreshold
181
confThreshold = pos / 100.0
182
183
cv.createTrackbar('Confidence threshold, %', winName, int(confThreshold * 100), 99, callback)
184
185
cap = cv.VideoCapture(args.input if args.input else 0)
186
while cv.waitKey(1) < 0:
187
hasFrame, frame = cap.read()
188
if not hasFrame:
189
cv.waitKey()
190
break
191
192
frameHeight = frame.shape[0]
193
frameWidth = frame.shape[1]
194
195
# Create a 4D blob from a frame.
196
inpWidth = args.width if args.width else frameWidth
197
inpHeight = args.height if args.height else frameHeight
198
blob = cv.dnn.blobFromImage(frame, args.scale, (inpWidth, inpHeight), args.mean, args.rgb, crop=False)
199
200
# Run a model
201
net.setInput(blob)
202
if net.getLayer(0).outputNameToIndex('im_info') != -1: # Faster-RCNN or R-FCN
203
frame = cv.resize(frame, (inpWidth, inpHeight))
204
net.setInput(np.array([[inpHeight, inpWidth, 1.6]], dtype=np.float32), 'im_info')
205
outs = net.forward(outNames)
206
207
postprocess(frame, outs)
208
209
# Put efficiency information.
210
t, _ = net.getPerfProfile()
211
label = 'Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())
212
cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
213
214
cv.imshow(winName, frame)
215
216