aboutsummaryrefslogtreecommitdiff
path: root/src/argaze/AreaOfInterest/AOIFeatures.py
blob: 0d9fce09b9f0804da6e4537ca4dc5fcb1ded3921 (plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#!/usr/bin/env python

from dataclasses import dataclass, field

from argaze import DataStructures, GazeFeatures

import cv2 as cv
import matplotlib.path as mpath
import numpy

@dataclass
class AreaOfInterest(numpy.ndarray):
    """Define 2D/3D Area Of Interest."""

    def dimension(self):
        """Number of coordinates coding area points positions."""
        return self.shape[1]

    def bounding_box(self):
        """Get area's bounding box."""

        min_x, min_y = numpy.min(self, axis=0)
        max_x, max_y = numpy.max(self, axis=0)

        return numpy.array([(min_x, min_y), (max_x, min_y), (max_x, max_y), (min_x, max_y)])

    def center(self):
        """Center of mass"""
        return self.mean(axis=0)

    def clockwise(self):
        """Get area points in clocwise order."""

        if self.dimension() != 2:
            raise RuntimeError(f'Bad area dimension ({self.dimension()})')

        O = self.center()
        OP = (self - O) / numpy.linalg.norm(self - O)
        angles = numpy.arctan2(OP[:, 1], OP[:, 0])

        return self[numpy.argsort(angles)]

    def looked(self, gaze_position):
        """Is gaze position inside area ?"""

        if self.dimension() != 2:
            raise RuntimeError(f'Bad area dimension ({self.dimension()})')

        return mpath.Path(self).contains_points([gaze_position])[0]

    def look_at(self, gaze_pixel):
        """Get where the area is looked using perpespective transformation."""

        if self.dimension() != 2:
            raise RuntimeError(f'Bad area dimension ({self.dimension()})')

        Src = self.clockwise()
        Src_origin = Src[0]
        Src = (Src - Src_origin).reshape((len(Src)), 2)

        Dst = numpy.array([[0., 0.], [1., 0.], [1., 1.], [0., 1.]]).astype(numpy.float32)

        P = cv.getPerspectiveTransform(Src, Dst)
        X = numpy.append(numpy.array(gaze_pixel - Src_origin), [1.0]).astype(numpy.float32)
        Y = numpy.dot(P, X)

        La = (Y/Y[2])[:-1]

        return numpy.around(La, 4).tolist()

    def looked_pixel(self, look_at):
        """Get which pixel is looked."""

        if self.dimension() != 2:
            raise RuntimeError(f'Bad area dimension ({self.dimension()})')

        Src = numpy.array([[0., 0.], [1., 0.], [1., 1.], [0., 1.]]).astype(numpy.float32)

        Dst = self.clockwise()
        Dst_origin = Dst[0]
        Dst = (Dst - Dst_origin).reshape((len(Dst)), 2)

        P = cv.getPerspectiveTransform(Src, Dst)
        X = numpy.array([look_at[0], look_at[1], 1.0]).astype(numpy.float32)
        Y = numpy.dot(P, X)

        Lp = Dst_origin + (Y/Y[2])[:-1]

        return numpy.rint(Lp).astype(int).tolist()

    def draw(self, frame, color):

        # Draw form
        pixels = numpy.rint(self).astype(int)
        cv.line(frame, pixels[-1], pixels[0], color, 1)
        for A, B in zip(pixels, pixels[1:]):
            cv.line(frame, A, B, color, 1)

        # Draw center
        center_pixel = numpy.rint(self.center()).astype(int)
        cv.circle(frame, center_pixel, 1, color, -1)

@dataclass
class AOIScene():
    """Define 2D/3D AOI scene."""

    dimension: int = field(init=False, repr=False, default=None)
    """Dimension of the AOIs in scene."""

    areas: dict = field(init=False, default_factory=dict)
    """All aois in the scene."""

    def __getitem__(self, key):
        """Get an aoi from the scene."""
        return numpy.array(self.areas[key]).astype(numpy.float32).view(AreaOfInterest)

    def __setitem__(self, name, aoi: AreaOfInterest):
        """Add an aoi to the scene."""
        self.areas[name] = aoi.tolist()

    def items(self):
        for name, area in self.areas.items():
            yield name, numpy.array(area).astype(numpy.float32).view(AreaOfInterest)

    def keys(self):
        return self.areas.keys()

class TimeStampedAOIScenes(DataStructures.TimeStampedBuffer):
    """Define timestamped buffer to store AOI scenes in time."""

    def __setitem__(self, key, value):
        """Force value to inherit from AOIScene."""
        if type(value).__bases__[0] != AOIScene:
            raise ValueError(f'value must inherit from AOIScene')

        super().__setitem__(key, value)