File size: 2,492 Bytes
a103028
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

import json
from math import floor

class PixelRect:
    def __init__(self, minX: int, minY: int, width: int, height: int):
        self.min_x = floor(minX)
        self.min_y = floor(minY)
        self.max_x = floor(minX + width)
        self.max_y = floor(minY + height)

        # Make width and height divisible by 4
        width  = int(width / 4) * 4
        height = int(height / 4) * 4

    @property
    def width(self):
        return self.max_x - self.min_x

    @property
    def height(self):
        return self.max_y - self.min_y

    def to_normalized_rect(self, width: int, height: int):
        return NormalizedRect(self.min_x / width, self.min_y / height, self.width / width, self.height / height)

    def String(self):
        return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True)

    def Print(self, stream):
        stream.write(self.String())

class NormalizedRect:
    def __init__(self, minX: float, minY: float, width: float, height: float):
        self.min_x = minX
        self.min_y = minY

        width = max(width, 0)
        width = min(width, 1)
        self.max_x = self.min_x + width

        height = max(height, 0)
        height = min(height, 1)
        self.max_y = self.min_y + height
    
    def to_pixel_rect(self, width: int, height: int):
        xmin   = self.min_x * width
        ymin   = self.min_y * height
        width  = self.width * width
        height = self.height * height

        return PixelRect(xmin, ymin, width, height)
        
    def union(self, x):
        if x.min_x >= 0:
            self.min_x = min(self.min_x, x.min_x)

        if x.min_y >= 0:
            self.min_y = min(self.min_y, x.min_y)

        if x.max_x <= 1:
            self.max_x = max(self.max_x, x.max_x)

        if x.max_y <= 1:
            self.max_y = max(self.max_y, x.max_y)

    def intersect(self, x):
        if x.min_x < 1:
            self.min_x = max(self.min_x, x.min_x)
    
        if x.min_y < 1:
            self.min_y = max(self.min_y, x.min_y)

        if x.max_x > 0:
            self.max_x = min(self.max_x, x.max_x)

        if x.max_y > 0:
            self.max_y = min(self.max_y, x.max_y)

    @property
    def width(self):
        return self.max_x - self.min_x

    @property
    def height(self):
        return self.max_y - self.min_y

    def String(self):
        return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True)

    def Print(self, stream):
        stream.write(self.String())