Publishing 2019 R1 content
[platform/upstream/dldt.git] / tools / accuracy_checker / accuracy_checker / postprocessor / cast_to_int.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 from functools import singledispatch
17 from typing import Union
18 import numpy as np
19 from ..config import StringField
20 from ..representation import DetectionAnnotation, DetectionPrediction, TextDetectionPrediction, TextDetectionAnnotation
21 from .postprocessor import Postprocessor, BasePostprocessorConfig
22
23
24 class CastToInt(Postprocessor):
25     __provider__ = 'cast_to_int'
26     annotation_types = (DetectionAnnotation, TextDetectionAnnotation)
27     prediction_types = (DetectionPrediction, TextDetectionPrediction)
28
29     round_policies_func = {
30         'nearest': np.rint,
31         'nearest_to_zero': np.trunc,
32         'lower': np.floor,
33         'greater': np.ceil
34     }
35
36     def validate_config(self):
37         class _CastToIntConfigValidator(BasePostprocessorConfig):
38             round_policy = StringField(optional=True, choices=self.round_policies_func.keys())
39
40         cast_to_int_config_validator = _CastToIntConfigValidator(
41             self.__provider__, on_extra_argument=_CastToIntConfigValidator.ERROR_ON_EXTRA_ARGUMENT
42         )
43         cast_to_int_config_validator.validate(self.config)
44
45     def configure(self):
46         self.round_func = self.round_policies_func[self.config.get('round_policy', 'nearest')]
47
48     def process_image(self, annotation, prediction):
49         @singledispatch
50         def cast(entry):
51             pass
52
53         @cast.register(Union[DetectionAnnotation, DetectionPrediction])
54         def _(entry):
55             entry.x_mins = self.round_func(entry.x_mins)
56             entry.x_maxs = self.round_func(entry.x_maxs)
57             entry.y_mins = self.round_func(entry.y_mins)
58             entry.y_maxs = self.round_func(entry.y_maxs)
59
60         @cast.register(Union[TextDetectionAnnotation, TextDetectionPrediction])
61         def _(entry):
62             entry.points = self.round_func(entry.points)
63
64
65         for annotation_ in annotation:
66             cast(annotation_)
67
68         for prediction_ in prediction:
69             cast(prediction_)
70
71         return annotation, prediction