2018-03-02 17:04:39 +08:00
|
|
|
import cv2 as cv
|
|
|
|
import argparse
|
|
|
|
import numpy as np
|
2019-05-08 20:27:22 +08:00
|
|
|
import sys
|
|
|
|
import time
|
|
|
|
from threading import Thread
|
2023-07-13 21:07:10 +08:00
|
|
|
import queue
|
2018-03-02 17:04:39 +08:00
|
|
|
|
2018-09-20 22:59:04 +08:00
|
|
|
from common import *
|
2018-09-03 22:08:40 +08:00
|
|
|
from tf_text_graph_common import readTextMessage
|
|
|
|
from tf_text_graph_ssd import createSSDGraph
|
|
|
|
from tf_text_graph_faster_rcnn import createFasterRCNNGraph
|
|
|
|
|
2021-06-01 22:00:51 +08:00
|
|
|
backends = (cv.dnn.DNN_BACKEND_DEFAULT, cv.dnn.DNN_BACKEND_HALIDE, cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_BACKEND_OPENCV,
|
|
|
|
cv.dnn.DNN_BACKEND_VKCOM, cv.dnn.DNN_BACKEND_CUDA)
|
|
|
|
targets = (cv.dnn.DNN_TARGET_CPU, cv.dnn.DNN_TARGET_OPENCL, cv.dnn.DNN_TARGET_OPENCL_FP16, cv.dnn.DNN_TARGET_MYRIAD, cv.dnn.DNN_TARGET_HDDL,
|
|
|
|
cv.dnn.DNN_TARGET_VULKAN, cv.dnn.DNN_TARGET_CUDA, cv.dnn.DNN_TARGET_CUDA_FP16)
|
2018-03-03 21:43:21 +08:00
|
|
|
|
2018-09-20 22:59:04 +08:00
|
|
|
parser = argparse.ArgumentParser(add_help=False)
|
|
|
|
parser.add_argument('--zoo', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models.yml'),
|
|
|
|
help='An optional path to file with preprocessing parameters.')
|
2018-03-02 17:04:39 +08:00
|
|
|
parser.add_argument('--input', help='Path to input image or video file. Skip this argument to capture frames from a camera.')
|
2018-09-03 22:08:40 +08:00
|
|
|
parser.add_argument('--out_tf_graph', default='graph.pbtxt',
|
|
|
|
help='For models from TensorFlow Object Detection API, you may '
|
|
|
|
'pass a .config file which was used for training through --config '
|
|
|
|
'argument. This way an additional .pbtxt file with TensorFlow graph will be created.')
|
|
|
|
parser.add_argument('--framework', choices=['caffe', 'tensorflow', 'torch', 'darknet', 'dldt'],
|
2018-03-02 17:04:39 +08:00
|
|
|
help='Optional name of an origin framework of the model. '
|
|
|
|
'Detect it automatically if it does not set.')
|
|
|
|
parser.add_argument('--thr', type=float, default=0.5, help='Confidence threshold')
|
2018-06-28 14:09:11 +08:00
|
|
|
parser.add_argument('--nms', type=float, default=0.4, help='Non-maximum suppression threshold')
|
2018-03-03 21:43:21 +08:00
|
|
|
parser.add_argument('--backend', choices=backends, default=cv.dnn.DNN_BACKEND_DEFAULT, type=int,
|
|
|
|
help="Choose one of computation backends: "
|
2018-06-01 15:54:12 +08:00
|
|
|
"%d: automatically (by default), "
|
2018-03-03 21:43:21 +08:00
|
|
|
"%d: Halide language (http://halide-lang.org/), "
|
2018-06-01 15:54:12 +08:00
|
|
|
"%d: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
|
2021-06-01 22:00:51 +08:00
|
|
|
"%d: OpenCV implementation, "
|
|
|
|
"%d: VKCOM, "
|
|
|
|
"%d: CUDA" % backends)
|
2018-03-03 21:43:21 +08:00
|
|
|
parser.add_argument('--target', choices=targets, default=cv.dnn.DNN_TARGET_CPU, type=int,
|
|
|
|
help='Choose one of target computation devices: '
|
|
|
|
'%d: CPU target (by default), '
|
2018-06-01 15:54:12 +08:00
|
|
|
'%d: OpenCL, '
|
|
|
|
'%d: OpenCL fp16 (half-float precision), '
|
2020-11-18 03:47:24 +08:00
|
|
|
'%d: NCS2 VPU, '
|
2021-06-01 22:00:51 +08:00
|
|
|
'%d: HDDL VPU, '
|
|
|
|
'%d: Vulkan, '
|
|
|
|
'%d: CUDA, '
|
|
|
|
'%d: CUDA fp16 (half-float preprocess)' % targets)
|
2019-05-08 20:27:22 +08:00
|
|
|
parser.add_argument('--async', type=int, default=0,
|
2020-01-23 23:43:36 +08:00
|
|
|
dest='asyncN',
|
2019-05-08 20:27:22 +08:00
|
|
|
help='Number of asynchronous forwards at the same time. '
|
|
|
|
'Choose 0 for synchronous mode')
|
2018-09-20 22:59:04 +08:00
|
|
|
args, _ = parser.parse_known_args()
|
|
|
|
add_preproc_args(args.zoo, parser, 'object_detection')
|
|
|
|
parser = argparse.ArgumentParser(parents=[parser],
|
|
|
|
description='Use this script to run object detection deep learning networks using OpenCV.',
|
|
|
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
2018-03-02 17:04:39 +08:00
|
|
|
args = parser.parse_args()
|
|
|
|
|
2018-09-20 22:59:04 +08:00
|
|
|
args.model = findFile(args.model)
|
|
|
|
args.config = findFile(args.config)
|
|
|
|
args.classes = findFile(args.classes)
|
|
|
|
|
2018-09-03 22:08:40 +08:00
|
|
|
# If config specified, try to load it as TensorFlow Object Detection API's pipeline.
|
|
|
|
config = readTextMessage(args.config)
|
|
|
|
if 'model' in config:
|
|
|
|
print('TensorFlow Object Detection API config detected')
|
|
|
|
if 'ssd' in config['model'][0]:
|
|
|
|
print('Preparing text graph representation for SSD model: ' + args.out_tf_graph)
|
|
|
|
createSSDGraph(args.model, args.config, args.out_tf_graph)
|
|
|
|
args.config = args.out_tf_graph
|
|
|
|
elif 'faster_rcnn' in config['model'][0]:
|
|
|
|
print('Preparing text graph representation for Faster-RCNN model: ' + args.out_tf_graph)
|
|
|
|
createFasterRCNNGraph(args.model, args.config, args.out_tf_graph)
|
|
|
|
args.config = args.out_tf_graph
|
|
|
|
|
|
|
|
|
2018-03-02 17:04:39 +08:00
|
|
|
# Load names of classes
|
|
|
|
classes = None
|
|
|
|
if args.classes:
|
|
|
|
with open(args.classes, 'rt') as f:
|
|
|
|
classes = f.read().rstrip('\n').split('\n')
|
|
|
|
|
|
|
|
# Load a network
|
2018-11-11 21:18:09 +08:00
|
|
|
net = cv.dnn.readNet(cv.samples.findFile(args.model), cv.samples.findFile(args.config), args.framework)
|
2018-03-03 21:43:21 +08:00
|
|
|
net.setPreferableBackend(args.backend)
|
|
|
|
net.setPreferableTarget(args.target)
|
2018-09-25 23:10:45 +08:00
|
|
|
outNames = net.getUnconnectedOutLayersNames()
|
2018-03-03 21:43:21 +08:00
|
|
|
|
2018-03-02 17:04:39 +08:00
|
|
|
confThreshold = args.thr
|
2018-06-28 14:09:11 +08:00
|
|
|
nmsThreshold = args.nms
|
2018-03-02 17:04:39 +08:00
|
|
|
|
2018-04-13 23:53:12 +08:00
|
|
|
def postprocess(frame, outs):
|
2018-03-02 17:04:39 +08:00
|
|
|
frameHeight = frame.shape[0]
|
|
|
|
frameWidth = frame.shape[1]
|
|
|
|
|
|
|
|
def drawPred(classId, conf, left, top, right, bottom):
|
|
|
|
# Draw a bounding box.
|
|
|
|
cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))
|
|
|
|
|
2018-04-13 23:53:12 +08:00
|
|
|
label = '%.2f' % conf
|
2018-03-02 17:04:39 +08:00
|
|
|
|
|
|
|
# Print a label of class.
|
|
|
|
if classes:
|
|
|
|
assert(classId < len(classes))
|
|
|
|
label = '%s: %s' % (classes[classId], label)
|
|
|
|
|
|
|
|
labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
|
|
|
|
top = max(top, labelSize[1])
|
|
|
|
cv.rectangle(frame, (left, top - labelSize[1]), (left + labelSize[0], top + baseLine), (255, 255, 255), cv.FILLED)
|
|
|
|
cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
|
|
|
|
|
|
|
|
layerNames = net.getLayerNames()
|
|
|
|
lastLayerId = net.getLayerId(layerNames[-1])
|
|
|
|
lastLayer = net.getLayer(lastLayerId)
|
|
|
|
|
2018-06-28 14:09:11 +08:00
|
|
|
classIds = []
|
|
|
|
confidences = []
|
|
|
|
boxes = []
|
2019-01-23 00:01:48 +08:00
|
|
|
if lastLayer.type == 'DetectionOutput':
|
2018-03-02 17:04:39 +08:00
|
|
|
# Network produces output blob with a shape 1x1xNx7 where N is a number of
|
|
|
|
# detections and an every detection is a vector of values
|
|
|
|
# [batchId, classId, confidence, left, top, right, bottom]
|
2018-06-28 14:09:11 +08:00
|
|
|
for out in outs:
|
|
|
|
for detection in out[0, 0]:
|
|
|
|
confidence = detection[2]
|
|
|
|
if confidence > confThreshold:
|
|
|
|
left = int(detection[3])
|
|
|
|
top = int(detection[4])
|
|
|
|
right = int(detection[5])
|
|
|
|
bottom = int(detection[6])
|
|
|
|
width = right - left + 1
|
|
|
|
height = bottom - top + 1
|
2019-09-13 16:50:50 +08:00
|
|
|
if width <= 2 or height <= 2:
|
2019-01-23 00:01:48 +08:00
|
|
|
left = int(detection[3] * frameWidth)
|
|
|
|
top = int(detection[4] * frameHeight)
|
|
|
|
right = int(detection[5] * frameWidth)
|
|
|
|
bottom = int(detection[6] * frameHeight)
|
|
|
|
width = right - left + 1
|
|
|
|
height = bottom - top + 1
|
2018-06-28 14:09:11 +08:00
|
|
|
classIds.append(int(detection[1]) - 1) # Skip background label
|
|
|
|
confidences.append(float(confidence))
|
|
|
|
boxes.append([left, top, width, height])
|
2018-03-02 17:04:39 +08:00
|
|
|
elif lastLayer.type == 'Region':
|
|
|
|
# Network produces output blob with a shape NxC where N is a number of
|
|
|
|
# detected objects and C is a number of classes + 4 where the first 4
|
|
|
|
# numbers are [center_x, center_y, width, height]
|
2018-04-13 23:53:12 +08:00
|
|
|
for out in outs:
|
|
|
|
for detection in out:
|
|
|
|
scores = detection[5:]
|
|
|
|
classId = np.argmax(scores)
|
|
|
|
confidence = scores[classId]
|
|
|
|
if confidence > confThreshold:
|
|
|
|
center_x = int(detection[0] * frameWidth)
|
|
|
|
center_y = int(detection[1] * frameHeight)
|
|
|
|
width = int(detection[2] * frameWidth)
|
|
|
|
height = int(detection[3] * frameHeight)
|
2018-08-30 23:21:54 +08:00
|
|
|
left = int(center_x - width / 2)
|
|
|
|
top = int(center_y - height / 2)
|
2018-04-13 23:53:12 +08:00
|
|
|
classIds.append(classId)
|
|
|
|
confidences.append(float(confidence))
|
|
|
|
boxes.append([left, top, width, height])
|
2018-06-28 14:09:11 +08:00
|
|
|
else:
|
|
|
|
print('Unknown output layer type: ' + lastLayer.type)
|
|
|
|
exit()
|
|
|
|
|
2020-05-25 20:34:11 +08:00
|
|
|
# NMS is used inside Region layer only on DNN_BACKEND_OPENCV for another backends we need NMS in sample
|
|
|
|
# or NMS is required if number of outputs > 1
|
|
|
|
if len(outNames) > 1 or lastLayer.type == 'Region' and args.backend != cv.dnn.DNN_BACKEND_OPENCV:
|
|
|
|
indices = []
|
|
|
|
classIds = np.array(classIds)
|
|
|
|
boxes = np.array(boxes)
|
|
|
|
confidences = np.array(confidences)
|
|
|
|
unique_classes = set(classIds)
|
|
|
|
for cl in unique_classes:
|
|
|
|
class_indices = np.where(classIds == cl)[0]
|
|
|
|
conf = confidences[class_indices]
|
|
|
|
box = boxes[class_indices].tolist()
|
|
|
|
nms_indices = cv.dnn.NMSBoxes(box, conf, confThreshold, nmsThreshold)
|
|
|
|
nms_indices = nms_indices[:, 0] if len(nms_indices) else []
|
|
|
|
indices.extend(class_indices[nms_indices])
|
|
|
|
else:
|
|
|
|
indices = np.arange(0, len(classIds))
|
|
|
|
|
2018-06-28 14:09:11 +08:00
|
|
|
for i in indices:
|
|
|
|
box = boxes[i]
|
|
|
|
left = box[0]
|
|
|
|
top = box[1]
|
|
|
|
width = box[2]
|
|
|
|
height = box[3]
|
|
|
|
drawPred(classIds[i], confidences[i], left, top, left + width, top + height)
|
2018-03-02 17:04:39 +08:00
|
|
|
|
|
|
|
# Process inputs
|
|
|
|
winName = 'Deep learning object detection in OpenCV'
|
|
|
|
cv.namedWindow(winName, cv.WINDOW_NORMAL)
|
|
|
|
|
|
|
|
def callback(pos):
|
|
|
|
global confThreshold
|
|
|
|
confThreshold = pos / 100.0
|
|
|
|
|
|
|
|
cv.createTrackbar('Confidence threshold, %', winName, int(confThreshold * 100), 99, callback)
|
|
|
|
|
2018-11-11 21:18:09 +08:00
|
|
|
cap = cv.VideoCapture(cv.samples.findFileOrKeep(args.input) if args.input else 0)
|
2019-05-08 20:27:22 +08:00
|
|
|
|
|
|
|
class QueueFPS(queue.Queue):
|
|
|
|
def __init__(self):
|
|
|
|
queue.Queue.__init__(self)
|
|
|
|
self.startTime = 0
|
|
|
|
self.counter = 0
|
|
|
|
|
|
|
|
def put(self, v):
|
|
|
|
queue.Queue.put(self, v)
|
|
|
|
self.counter += 1
|
|
|
|
if self.counter == 1:
|
|
|
|
self.startTime = time.time()
|
|
|
|
|
|
|
|
def getFPS(self):
|
|
|
|
return self.counter / (time.time() - self.startTime)
|
|
|
|
|
|
|
|
|
|
|
|
process = True
|
|
|
|
|
|
|
|
#
|
|
|
|
# Frames capturing thread
|
|
|
|
#
|
|
|
|
framesQueue = QueueFPS()
|
|
|
|
def framesThreadBody():
|
|
|
|
global framesQueue, process
|
|
|
|
|
|
|
|
while process:
|
|
|
|
hasFrame, frame = cap.read()
|
|
|
|
if not hasFrame:
|
|
|
|
break
|
|
|
|
framesQueue.put(frame)
|
|
|
|
|
|
|
|
|
|
|
|
#
|
|
|
|
# Frames processing thread
|
|
|
|
#
|
|
|
|
processedFramesQueue = queue.Queue()
|
|
|
|
predictionsQueue = QueueFPS()
|
|
|
|
def processingThreadBody():
|
|
|
|
global processedFramesQueue, predictionsQueue, args, process
|
|
|
|
|
|
|
|
futureOutputs = []
|
|
|
|
while process:
|
|
|
|
# Get a next frame
|
|
|
|
frame = None
|
|
|
|
try:
|
|
|
|
frame = framesQueue.get_nowait()
|
|
|
|
|
2020-01-23 23:43:36 +08:00
|
|
|
if args.asyncN:
|
|
|
|
if len(futureOutputs) == args.asyncN:
|
2019-05-08 20:27:22 +08:00
|
|
|
frame = None # Skip the frame
|
|
|
|
else:
|
|
|
|
framesQueue.queue.clear() # Skip the rest of frames
|
|
|
|
except queue.Empty:
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
if not frame is None:
|
|
|
|
frameHeight = frame.shape[0]
|
|
|
|
frameWidth = frame.shape[1]
|
|
|
|
|
|
|
|
# Create a 4D blob from a frame.
|
|
|
|
inpWidth = args.width if args.width else frameWidth
|
|
|
|
inpHeight = args.height if args.height else frameHeight
|
|
|
|
blob = cv.dnn.blobFromImage(frame, size=(inpWidth, inpHeight), swapRB=args.rgb, ddepth=cv.CV_8U)
|
|
|
|
processedFramesQueue.put(frame)
|
|
|
|
|
|
|
|
# Run a model
|
|
|
|
net.setInput(blob, scalefactor=args.scale, mean=args.mean)
|
|
|
|
if net.getLayer(0).outputNameToIndex('im_info') != -1: # Faster-RCNN or R-FCN
|
|
|
|
frame = cv.resize(frame, (inpWidth, inpHeight))
|
|
|
|
net.setInput(np.array([[inpHeight, inpWidth, 1.6]], dtype=np.float32), 'im_info')
|
|
|
|
|
2020-01-23 23:43:36 +08:00
|
|
|
if args.asyncN:
|
2019-05-08 20:27:22 +08:00
|
|
|
futureOutputs.append(net.forwardAsync())
|
|
|
|
else:
|
|
|
|
outs = net.forward(outNames)
|
|
|
|
predictionsQueue.put(np.copy(outs))
|
|
|
|
|
2019-05-01 19:51:12 +08:00
|
|
|
while futureOutputs and futureOutputs[0].wait_for(0):
|
2019-05-08 20:27:22 +08:00
|
|
|
out = futureOutputs[0].get()
|
|
|
|
predictionsQueue.put(np.copy([out]))
|
|
|
|
|
|
|
|
del futureOutputs[0]
|
|
|
|
|
|
|
|
|
|
|
|
framesThread = Thread(target=framesThreadBody)
|
|
|
|
framesThread.start()
|
|
|
|
|
|
|
|
processingThread = Thread(target=processingThreadBody)
|
|
|
|
processingThread.start()
|
|
|
|
|
|
|
|
#
|
|
|
|
# Postprocessing and rendering loop
|
|
|
|
#
|
2018-03-02 17:04:39 +08:00
|
|
|
while cv.waitKey(1) < 0:
|
2019-05-08 20:27:22 +08:00
|
|
|
try:
|
|
|
|
# Request prediction first because they put after frames
|
|
|
|
outs = predictionsQueue.get_nowait()
|
|
|
|
frame = processedFramesQueue.get_nowait()
|
2018-03-02 17:04:39 +08:00
|
|
|
|
2019-05-08 20:27:22 +08:00
|
|
|
postprocess(frame, outs)
|
|
|
|
|
|
|
|
# Put efficiency information.
|
|
|
|
if predictionsQueue.counter > 1:
|
|
|
|
label = 'Camera: %.2f FPS' % (framesQueue.getFPS())
|
|
|
|
cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
|
2018-03-02 17:04:39 +08:00
|
|
|
|
2019-05-08 20:27:22 +08:00
|
|
|
label = 'Network: %.2f FPS' % (predictionsQueue.getFPS())
|
|
|
|
cv.putText(frame, label, (0, 30), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
|
2018-03-02 17:04:39 +08:00
|
|
|
|
2019-05-08 20:27:22 +08:00
|
|
|
label = 'Skipped frames: %d' % (framesQueue.counter - predictionsQueue.counter)
|
|
|
|
cv.putText(frame, label, (0, 45), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
|
2018-03-02 17:04:39 +08:00
|
|
|
|
2019-05-08 20:27:22 +08:00
|
|
|
cv.imshow(winName, frame)
|
|
|
|
except queue.Empty:
|
|
|
|
pass
|
2018-03-02 17:04:39 +08:00
|
|
|
|
|
|
|
|
2019-05-08 20:27:22 +08:00
|
|
|
process = False
|
|
|
|
framesThread.join()
|
|
|
|
processingThread.join()
|