Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/dnn/mask_rcnn.py
16337 views
1
import cv2 as cv
2
import argparse
3
import numpy as np
4
5
parser = argparse.ArgumentParser(description=
6
'Use this script to run Mask-RCNN object detection and semantic '
7
'segmentation network from TensorFlow Object Detection API.')
8
parser.add_argument('--input', help='Path to input image or video file. Skip this argument to capture frames from a camera.')
9
parser.add_argument('--model', required=True, help='Path to a .pb file with weights.')
10
parser.add_argument('--config', required=True, help='Path to a .pxtxt file contains network configuration.')
11
parser.add_argument('--classes', help='Optional path to a text file with names of classes.')
12
parser.add_argument('--colors', help='Optional path to a text file with colors for an every class. '
13
'An every color is represented with three values from 0 to 255 in BGR channels order.')
14
parser.add_argument('--width', type=int, default=800,
15
help='Preprocess input image by resizing to a specific width.')
16
parser.add_argument('--height', type=int, default=800,
17
help='Preprocess input image by resizing to a specific height.')
18
parser.add_argument('--thr', type=float, default=0.5, help='Confidence threshold')
19
args = parser.parse_args()
20
21
np.random.seed(324)
22
23
# Load names of classes
24
classes = None
25
if args.classes:
26
with open(args.classes, 'rt') as f:
27
classes = f.read().rstrip('\n').split('\n')
28
29
# Load colors
30
colors = None
31
if args.colors:
32
with open(args.colors, 'rt') as f:
33
colors = [np.array(color.split(' '), np.uint8) for color in f.read().rstrip('\n').split('\n')]
34
35
legend = None
36
def showLegend(classes):
37
global legend
38
if not classes is None and legend is None:
39
blockHeight = 30
40
assert(len(classes) == len(colors))
41
42
legend = np.zeros((blockHeight * len(colors), 200, 3), np.uint8)
43
for i in range(len(classes)):
44
block = legend[i * blockHeight:(i + 1) * blockHeight]
45
block[:,:] = colors[i]
46
cv.putText(block, classes[i], (0, blockHeight/2), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))
47
48
cv.namedWindow('Legend', cv.WINDOW_NORMAL)
49
cv.imshow('Legend', legend)
50
classes = None
51
52
53
def drawBox(frame, classId, conf, left, top, right, bottom):
54
# Draw a bounding box.
55
cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))
56
57
label = '%.2f' % conf
58
59
# Print a label of class.
60
if classes:
61
assert(classId < len(classes))
62
label = '%s: %s' % (classes[classId], label)
63
64
labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
65
top = max(top, labelSize[1])
66
cv.rectangle(frame, (left, top - labelSize[1]), (left + labelSize[0], top + baseLine), (255, 255, 255), cv.FILLED)
67
cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
68
69
70
# Load a network
71
net = cv.dnn.readNet(args.model, args.config)
72
net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
73
74
winName = 'Mask-RCNN in OpenCV'
75
cv.namedWindow(winName, cv.WINDOW_NORMAL)
76
77
cap = cv.VideoCapture(args.input if args.input else 0)
78
legend = None
79
while cv.waitKey(1) < 0:
80
hasFrame, frame = cap.read()
81
if not hasFrame:
82
cv.waitKey()
83
break
84
85
frameH = frame.shape[0]
86
frameW = frame.shape[1]
87
88
# Create a 4D blob from a frame.
89
blob = cv.dnn.blobFromImage(frame, size=(args.width, args.height), swapRB=True, crop=False)
90
91
# Run a model
92
net.setInput(blob)
93
94
boxes, masks = net.forward(['detection_out_final', 'detection_masks'])
95
96
numClasses = masks.shape[1]
97
numDetections = boxes.shape[2]
98
99
# Draw segmentation
100
if not colors:
101
# Generate colors
102
colors = [np.array([0, 0, 0], np.uint8)]
103
for i in range(1, numClasses + 1):
104
colors.append((colors[i - 1] + np.random.randint(0, 256, [3], np.uint8)) / 2)
105
del colors[0]
106
107
boxesToDraw = []
108
for i in range(numDetections):
109
box = boxes[0, 0, i]
110
mask = masks[i]
111
score = box[2]
112
if score > args.thr:
113
classId = int(box[1])
114
left = int(frameW * box[3])
115
top = int(frameH * box[4])
116
right = int(frameW * box[5])
117
bottom = int(frameH * box[6])
118
119
left = max(0, min(left, frameW - 1))
120
top = max(0, min(top, frameH - 1))
121
right = max(0, min(right, frameW - 1))
122
bottom = max(0, min(bottom, frameH - 1))
123
124
boxesToDraw.append([frame, classId, score, left, top, right, bottom])
125
126
classMask = mask[classId]
127
classMask = cv.resize(classMask, (right - left + 1, bottom - top + 1))
128
mask = (classMask > 0.5)
129
130
roi = frame[top:bottom+1, left:right+1][mask]
131
frame[top:bottom+1, left:right+1][mask] = (0.7 * colors[classId] + 0.3 * roi).astype(np.uint8)
132
133
for box in boxesToDraw:
134
drawBox(*box)
135
136
# Put efficiency information.
137
t, _ = net.getPerfProfile()
138
label = 'Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())
139
cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
140
141
showLegend(classes)
142
143
cv.imshow(winName, frame)
144
145