File size: 1,904 Bytes
983d4ef |
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 |
from typing import Dict, NamedTuple, Tuple
import numpy as np
class Point(NamedTuple):
x: int
y: int
class Landmarks(NamedTuple):
eye1: Point
eye2: Point
nose: Point
mouth1: Point
mouth2: Point
class Rect:
def __init__(
self,
left: int,
top: int,
right: int,
bottom: int,
tag: str = "face",
landmarks: Landmarks = None,
attributes: Dict[str, str] = {},
) -> None:
self.tag = tag
self.left = left
self.top = top
self.right = right
self.bottom = bottom
self.center = int((right + left) / 2)
self.middle = int((top + bottom) / 2)
self.width = right - left
self.height = bottom - top
self.size = self.width * self.height
self.landmarks = landmarks
self.attributes = attributes
@classmethod
def from_ndarray(
cls,
face_box: np.ndarray,
tag: str = "face",
landmarks: Landmarks = None,
attributes: Dict[str, str] = {},
) -> "Rect":
left, top, right, bottom, *_ = list(map(int, face_box))
return cls(left, top, right, bottom, tag, landmarks, attributes)
def to_tuple(self) -> Tuple[int, int, int, int]:
return self.left, self.top, self.right, self.bottom
def to_square(self):
left, top, right, bottom = self.to_tuple()
width = right - left
height = bottom - top
if width % 2 == 1:
right = right + 1
width = width + 1
if height % 2 == 1:
bottom = bottom + 1
height = height + 1
diff = int(abs(width - height) / 2)
if width > height:
top = top - diff
bottom = bottom + diff
else:
left = left - diff
right = right + diff
return left, top, right, bottom
|