Publishing 2019 R1 content
[platform/upstream/dldt.git] / tools / accuracy_checker / accuracy_checker / postprocessor / extend_segmentation_mask.py
1 """
2 Copyright (c) 2019 Intel Corporation
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 """
16 import math
17 import cv2
18
19 from .postprocessor import Postprocessor, BasePostprocessorConfig
20 from ..representation import SegmentationAnnotation, SegmentationPrediction
21 from ..config import NumberField, ConfigError
22
23
24 class ExtendSegmentationMask(Postprocessor):
25     """
26     Extend annotation segmentation mask to prediction size filling border with specific label.
27     """
28
29     __provider__ = 'extend_segmentation_mask'
30
31     annotation_types = (SegmentationAnnotation, )
32     prediction_types = (SegmentationPrediction, )
33
34     def validate_config(self):
35         class _ExtendSegmentationMaskConfigValidator(BasePostprocessorConfig):
36             filling_label = NumberField(optional=True, floats=False)
37
38         extend_mask_config_validator = _ExtendSegmentationMaskConfigValidator(
39             self.__provider__, on_extra_argument=_ExtendSegmentationMaskConfigValidator.ERROR_ON_EXTRA_ARGUMENT
40         )
41         extend_mask_config_validator.validate(self.config)
42
43     def configure(self):
44         self.filling_label = self.config.get('filling_label', 255)
45
46     def process_image(self, annotation, prediction):
47         for annotation_, prediction_ in zip(annotation, prediction):
48             annotation_mask = annotation_.mask
49             dst_height, dst_width = prediction_.mask.shape[-2:]
50             height, width = annotation_mask.shape[-2:]
51             if dst_width < width or dst_height < height:
52                 raise ConfigError('size for extending should be not less current mask size')
53             pad = []
54             pad.append(int(math.floor((dst_height - height) / 2.0)))
55             pad.append(int(math.floor((dst_width - width) / 2.0)))
56             pad.append(int(dst_height - height - pad[0]))
57             pad.append(int(dst_width - width - pad[1]))
58
59             extended_mask = cv2.copyMakeBorder(
60                 annotation_mask, pad[0], pad[2], pad[1], pad[3], cv2.BORDER_CONSTANT, value=self.filling_label
61             )
62             annotation_.mask = extended_mask
63
64         return annotation, prediction