Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/dnn/segmentation.py
16337 views
1
import cv2 as cv
2
import argparse
3
import numpy as np
4
import sys
5
6
from common import *
7
8
backends = (cv.dnn.DNN_BACKEND_DEFAULT, cv.dnn.DNN_BACKEND_HALIDE, cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_BACKEND_OPENCV)
9
targets = (cv.dnn.DNN_TARGET_CPU, cv.dnn.DNN_TARGET_OPENCL, cv.dnn.DNN_TARGET_OPENCL_FP16, cv.dnn.DNN_TARGET_MYRIAD)
10
11
parser = argparse.ArgumentParser(add_help=False)
12
parser.add_argument('--zoo', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models.yml'),
13
help='An optional path to file with preprocessing parameters.')
14
parser.add_argument('--input', help='Path to input image or video file. Skip this argument to capture frames from a camera.')
15
parser.add_argument('--framework', choices=['caffe', 'tensorflow', 'torch', 'darknet'],
16
help='Optional name of an origin framework of the model. '
17
'Detect it automatically if it does not set.')
18
parser.add_argument('--colors', help='Optional path to a text file with colors for an every class. '
19
'An every color is represented with three values from 0 to 255 in BGR channels order.')
20
parser.add_argument('--backend', choices=backends, default=cv.dnn.DNN_BACKEND_DEFAULT, type=int,
21
help="Choose one of computation backends: "
22
"%d: automatically (by default), "
23
"%d: Halide language (http://halide-lang.org/), "
24
"%d: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
25
"%d: OpenCV implementation" % backends)
26
parser.add_argument('--target', choices=targets, default=cv.dnn.DNN_TARGET_CPU, type=int,
27
help='Choose one of target computation devices: '
28
'%d: CPU target (by default), '
29
'%d: OpenCL, '
30
'%d: OpenCL fp16 (half-float precision), '
31
'%d: VPU' % targets)
32
args, _ = parser.parse_known_args()
33
add_preproc_args(args.zoo, parser, 'segmentation')
34
parser = argparse.ArgumentParser(parents=[parser],
35
description='Use this script to run semantic segmentation deep learning networks using OpenCV.',
36
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
37
args = parser.parse_args()
38
39
args.model = findFile(args.model)
40
args.config = findFile(args.config)
41
args.classes = findFile(args.classes)
42
43
np.random.seed(324)
44
45
# Load names of classes
46
classes = None
47
if args.classes:
48
with open(args.classes, 'rt') as f:
49
classes = f.read().rstrip('\n').split('\n')
50
51
# Load colors
52
colors = None
53
if args.colors:
54
with open(args.colors, 'rt') as f:
55
colors = [np.array(color.split(' '), np.uint8) for color in f.read().rstrip('\n').split('\n')]
56
57
legend = None
58
def showLegend(classes):
59
global legend
60
if not classes is None and legend is None:
61
blockHeight = 30
62
assert(len(classes) == len(colors))
63
64
legend = np.zeros((blockHeight * len(colors), 200, 3), np.uint8)
65
for i in range(len(classes)):
66
block = legend[i * blockHeight:(i + 1) * blockHeight]
67
block[:,:] = colors[i]
68
cv.putText(block, classes[i], (0, blockHeight/2), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))
69
70
cv.namedWindow('Legend', cv.WINDOW_NORMAL)
71
cv.imshow('Legend', legend)
72
classes = None
73
74
# Load a network
75
net = cv.dnn.readNet(args.model, args.config, args.framework)
76
net.setPreferableBackend(args.backend)
77
net.setPreferableTarget(args.target)
78
79
winName = 'Deep learning image classification in OpenCV'
80
cv.namedWindow(winName, cv.WINDOW_NORMAL)
81
82
cap = cv.VideoCapture(args.input if args.input else 0)
83
legend = None
84
while cv.waitKey(1) < 0:
85
hasFrame, frame = cap.read()
86
if not hasFrame:
87
cv.waitKey()
88
break
89
90
frameHeight = frame.shape[0]
91
frameWidth = frame.shape[1]
92
93
# Create a 4D blob from a frame.
94
inpWidth = args.width if args.width else frameWidth
95
inpHeight = args.height if args.height else frameHeight
96
blob = cv.dnn.blobFromImage(frame, args.scale, (inpWidth, inpHeight), args.mean, args.rgb, crop=False)
97
98
# Run a model
99
net.setInput(blob)
100
score = net.forward()
101
102
numClasses = score.shape[1]
103
height = score.shape[2]
104
width = score.shape[3]
105
106
# Draw segmentation
107
if not colors:
108
# Generate colors
109
colors = [np.array([0, 0, 0], np.uint8)]
110
for i in range(1, numClasses):
111
colors.append((colors[i - 1] + np.random.randint(0, 256, [3], np.uint8)) / 2)
112
113
classIds = np.argmax(score[0], axis=0)
114
segm = np.stack([colors[idx] for idx in classIds.flatten()])
115
segm = segm.reshape(height, width, 3)
116
117
segm = cv.resize(segm, (frameWidth, frameHeight), interpolation=cv.INTER_NEAREST)
118
frame = (0.1 * frame + 0.9 * segm).astype(np.uint8)
119
120
# Put efficiency information.
121
t, _ = net.getPerfProfile()
122
label = 'Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())
123
cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
124
125
showLegend(classes)
126
127
cv.imshow(winName, frame)
128
129