Skip to content

Commit 1c51d36

Browse files
author
Dmitry Sidnev
committed
Fixes
1 parent 7591ae0 commit 1c51d36

File tree

2 files changed

+73
-36
lines changed

2 files changed

+73
-36
lines changed

demos/background_subtraction_demo/python/background_subtraction_demo.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -126,10 +126,13 @@ def fit_to_window(input_img, output_resolution):
126126

127127

128128
def render_results(frame, objects, output_resolution, target_bgr, person_id, blur_bgr=False, show_with_original_frame=False):
129+
blur_kernel = (11, 11)
129130
if target_bgr is None:
130-
target_bgr = np.full(frame.shape, [155, 255, 120], dtype=np.uint8)
131+
target_bgr = cv2.blur(frame, blur_kernel) if blur_bgr else np.full(frame.shape, [155, 255, 120], dtype=np.uint8)
131132
else:
132133
target_bgr = cv2.resize(target_bgr, (frame.shape[1], frame.shape[0]))
134+
if blur_bgr:
135+
target_bgr = cv2.blur(target_bgr, blur_kernel)
133136
classes, masks = objects[1], objects[3]
134137
# Choose masks only for person class
135138
valid_inds = classes == person_id
@@ -143,8 +146,6 @@ def render_results(frame, objects, output_resolution, target_bgr, person_id, blu
143146
# Smooth contours of the predicted mask
144147
composed_mask = cv2.medianBlur(composed_mask.astype(np.uint8), 11)
145148
composed_mask = np.repeat(np.expand_dims(composed_mask, axis=-1), 3, axis=2)
146-
if target_bgr is not None and blur_bgr:
147-
target_bgr = cv2.blur(cv2.resize(target_bgr, (target_bgr.shape[1], target_bgr.shape[0])), (7, 7))
148149
output = np.where(composed_mask == 1, frame, target_bgr)
149150
if show_with_original_frame:
150151
output = cv2.hconcat([frame, output])
@@ -172,8 +173,14 @@ def main():
172173

173174
labels = ['__background__', 'person'] if args.labels is None else args.labels
174175

175-
model = get_instance_segmentation_model(model_adapter, prob_threshold=args.prob_threshold,
176-
labels=labels, keep_aspect_ratio=args.keep_aspect_ratio)
176+
configuration = dict(
177+
prob_threshold=args.prob_threshold,
178+
labels=labels,
179+
resize_type='fit_to_window' if args.keep_aspect_ratio else 'standard'
180+
)
181+
182+
model = get_instance_segmentation_model(model_adapter, configuration)
183+
177184
person_id = -1
178185
for i, label in enumerate(labels):
179186
if label == 'person':

demos/common/python/openvino/model_zoo/model_api/models/instance_segmentation.py

Lines changed: 61 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -18,26 +18,42 @@
1818
import numpy as np
1919

2020
from .image_model import ImageModel
21-
from .utils import RESIZE_TYPES, load_labels, nms, pad_image
21+
from .model import WrapperError
22+
from .types import ListValue, NumericalValue
23+
from .utils import load_labels, nms
2224

2325

2426
class MaskRCNNModel(ImageModel):
25-
def __init__(self, model_adapter, prob_threshold=0.5, labels=None, keep_aspect_ratio=False):
26-
super().__init__(model_adapter)
27-
self.resize_type = 'fit_to_window' if keep_aspect_ratio else 'standard'
28-
self.resize = RESIZE_TYPES[self.resize_type]
29-
self.prob_threshold = prob_threshold
27+
__model__ = 'MaskRCNN'
28+
29+
def __init__(self, model_adapter, configuration):
30+
super().__init__(model_adapter, configuration)
3031
self._check_io_number((1, 2), (3, 4, 5, 8))
31-
self.type = 'segmentoly' if len(self.inputs) == 2 else 'mask_rcnn'
32-
if isinstance(labels, (list, tuple)):
33-
self.labels = labels
32+
self.is_segmentoly = len(self.inputs) == 2
33+
if isinstance(self.labels, (list, tuple)):
34+
self.labels = self.labels
3435
else:
35-
self.labels = load_labels(labels) if labels else None
36+
self.labels = load_labels(self.labels) if self.labels else None
3637

3738
self.output_blob_name = self._get_outputs()
3839

40+
@classmethod
41+
def parameters(cls):
42+
parameters = super().parameters()
43+
parameters.update({
44+
'prob_threshold': NumericalValue(
45+
default_value=None,
46+
description='Probability threshold for detections filtering'
47+
),
48+
'labels': ListValue(
49+
default_value=None,
50+
description='List of labels'
51+
),
52+
})
53+
return parameters
54+
3955
def _get_outputs(self):
40-
if self.type == 'segmentoly':
56+
if self.is_segmentoly:
4157
return self._get_segmentoly_outputs()
4258
outputs = {}
4359
for layer_name in self.outputs:
@@ -52,7 +68,7 @@ def _get_outputs(self):
5268
elif len(layer_shape) == 3:
5369
outputs['masks'] = layer_name
5470
else:
55-
raise Exception("Unexpected output layer shape {} with name {}".format(layer_shape, layer_name))
71+
raise WrapperError(self.__model__, "Unexpected output layer shape {} with name {}".format(layer_shape, layer_name))
5672

5773
return outputs
5874

@@ -69,34 +85,34 @@ def _get_segmentoly_outputs(self):
6985
elif layer_name == 'raw_masks' and len(layer_shape) == 4:
7086
outputs['masks'] = layer_name
7187
else:
72-
raise Exception("Unexpected output layer shape {} with name {}".format(layer_shape, layer_name))
88+
raise WrapperError(self.__model__, "Unexpected output layer shape {} with name {}".format(layer_shape, layer_name))
7389
return outputs
7490

7591
def preprocess(self, inputs):
7692
dict_inputs, meta = super().preprocess(inputs)
77-
input_image_size = meta['resized_shape'].shape[:2]
78-
if self.type == 'segmentoly':
93+
input_image_size = meta['resized_shape'][:2]
94+
if self.is_segmentoly:
7995
assert len(self.image_info_blob_names) == 1
8096
input_image_info = np.asarray([[input_image_size[0], input_image_size[1], 1]], dtype=np.float32)
8197
dict_inputs[self.image_info_blob_names[0]] = input_image_info
8298
return dict_inputs, meta
8399

84100
def postprocess(self, outputs, meta):
85-
boxes = outputs[self.output_blob_name['boxes']] if self.type == 'segmentoly' else \
101+
boxes = outputs[self.output_blob_name['boxes']] if self.is_segmentoly else \
86102
outputs[self.output_blob_name['boxes']][:, :4]
87-
scores = outputs[self.output_blob_name['scores']] if self.type == 'segmentoly' else \
103+
scores = outputs[self.output_blob_name['scores']] if self.is_segmentoly else \
88104
outputs[self.output_blob_name['boxes']][:, 4]
89105
scale_x = meta['resized_shape'][1] / meta['original_shape'][1]
90106
scale_y = meta['resized_shape'][0] / meta['original_shape'][0]
91107
boxes[:, 0::2] /= scale_x
92108
boxes[:, 1::2] /= scale_y
93-
if self.type == 'segmentoly':
109+
if self.is_segmentoly:
94110
classes = outputs[self.output_blob_name['labels']].astype(np.uint32)
95111
else:
96112
classes = outputs[self.output_blob_name['labels']].astype(np.uint32) + 1
97113
masks = []
98114
for box, cls, raw_mask in zip(boxes, classes, outputs[self.output_blob_name['masks']]):
99-
raw_cls_mask = raw_mask[cls, ...] if self.type == 'segmentoly' else raw_mask
115+
raw_cls_mask = raw_mask[cls, ...] if self.is_segmentoly else raw_mask
100116
masks.append(self._segm_postprocess(box, raw_cls_mask, *meta['original_shape'][:-1]))
101117
# Filter out detections with low confidence.
102118
detections_filter = scores > self.prob_threshold
@@ -139,19 +155,33 @@ def _segm_postprocess(self, box, raw_cls_mask, im_h, im_w):
139155

140156

141157
class YolactModel(ImageModel):
142-
def __init__(self, model_adapter, prob_threshold=0.5, labels=None, keep_aspect_ratio=False):
143-
super().__init__(model_adapter)
144-
self.resize_type = 'fit_to_window' if keep_aspect_ratio else 'standard'
145-
self.resize = RESIZE_TYPES[self.resize_type]
146-
self.prob_threshold = prob_threshold
158+
__model__ = 'Yolact'
159+
160+
def __init__(self, model_adapter, configuration):
161+
super().__init__(model_adapter, configuration)
147162
self._check_io_number(1, 4)
148-
if isinstance(labels, (list, tuple)):
149-
self.labels = labels
163+
if isinstance(self.labels, (list, tuple)):
164+
self.labels = self.labels
150165
else:
151-
self.labels = load_labels(labels) if labels else None
166+
self.labels = load_labels(self.labels) if self.labels else None
152167

153168
self.output_blob_name = self._get_outputs()
154169

170+
@classmethod
171+
def parameters(cls):
172+
parameters = super().parameters()
173+
parameters.update({
174+
'prob_threshold': NumericalValue(
175+
default_value=None,
176+
description='Probability threshold for detections filtering'
177+
),
178+
'labels': ListValue(
179+
default_value=None,
180+
description='List of labels'
181+
),
182+
})
183+
return parameters
184+
155185
def _get_outputs(self):
156186
outputs = {}
157187
for layer_name in self.outputs:
@@ -165,7 +195,7 @@ def _get_outputs(self):
165195
elif layer_name == 'mask' and len(layer_shape) == 3:
166196
outputs['masks'] = layer_name
167197
else:
168-
raise Exception("Unexpected output layer shape {} with name {}".format(layer_shape, layer_name))
198+
raise WrapperError(self.__model__, "Unexpected output layer shape {} with name {}".format(layer_shape, layer_name))
169199
return outputs
170200

171201
def postprocess(self, outputs, meta):
@@ -276,10 +306,10 @@ def _sanitize_coordinates(_x1, _x2, img_size, shift=0, padding=0):
276306
return x1, x2
277307

278308

279-
def get_instance_segmentation_model(model_adapter, prob_threshold=0.5, labels=None, keep_aspect_ratio=False):
309+
def get_instance_segmentation_model(model_adapter, configuration):
280310
inputs = model_adapter.get_input_layers()
281311
outputs = model_adapter.get_output_layers()
282312
if len(inputs) == 1 and len(outputs) == 4 and 'proto' in outputs.keys():
283-
return YolactModel(model_adapter, prob_threshold, labels, keep_aspect_ratio)
313+
return YolactModel(model_adapter, configuration)
284314
else:
285-
return MaskRCNNModel(model_adapter, prob_threshold, labels, keep_aspect_ratio)
315+
return MaskRCNNModel(model_adapter, configuration)

0 commit comments

Comments
 (0)