Publishing 2019 R1 content
[platform/upstream/dldt.git] / tools / accuracy_checker / accuracy_checker / metrics / overlap.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
17 import numpy as np
18
19 from ..dependency import ClassProvider
20
21
22 class Overlap(ClassProvider):
23     __provider_type__ = 'overlap'
24
25     @staticmethod
26     def intersections(prediction_box, annotation_boxes):
27         px_min, py_min, px_max, py_max = prediction_box
28         ax_mins, ay_mins, ax_maxs, ay_maxs = annotation_boxes
29
30         x_mins = np.maximum(ax_mins, px_min)
31         y_mins = np.maximum(ay_mins, py_min)
32         x_maxs = np.minimum(ax_maxs, px_max)
33         y_maxs = np.minimum(ay_maxs, py_max)
34
35         return x_mins, y_mins, np.maximum(x_mins, x_maxs), np.maximum(y_mins, y_maxs)
36
37     def __init__(self, include_boundaries=None):
38         self.boundary = 1 if include_boundaries else 0
39
40     def __call__(self, *args, **kwargs):
41         return self.evaluate(*args, **kwargs)
42
43     def evaluate(self, prediction_box, annotation_boxes):
44         raise NotImplementedError
45
46     def area(self, box):
47         x0, y0, x1, y1 = box
48         return (x1 - x0 + self.boundary) * (y1 - y0 + self.boundary)
49
50
51 class IOU(Overlap):
52     __provider__ = 'iou'
53
54     def evaluate(self, prediction_box, annotation_boxes):
55         intersections_area = self.area(self.intersections(prediction_box, annotation_boxes))
56         unions = self.area(prediction_box) + self.area(annotation_boxes) - intersections_area
57         return np.divide(
58             intersections_area, unions, out=np.zeros_like(intersections_area, dtype=float), where=unions != 0
59         )
60
61
62 class IOA(Overlap):
63     __provider__ = 'ioa'
64
65     def evaluate(self, prediction_box, annotation_boxes):
66         intersections_area = self.area(self.intersections(prediction_box, annotation_boxes))
67         prediction_area = self.area(prediction_box)
68         return np.divide(
69             intersections_area, prediction_area, out=np.zeros_like(intersections_area, dtype=float),
70             where=prediction_area != 0
71         )