|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace AhmadMayahi\Vision\Detectors\ObjectLocalizer; |
|
6
|
|
|
|
|
7
|
|
|
use AhmadMayahi\Vision\Contracts\Drawable; |
|
8
|
|
|
use AhmadMayahi\Vision\Data\LocalizedObject as LocalizedObjectData; |
|
9
|
|
|
use AhmadMayahi\Vision\Detectors\ObjectLocalizer; |
|
10
|
|
|
use AhmadMayahi\Vision\Enums\Color; |
|
11
|
|
|
use AhmadMayahi\Vision\Support\Image; |
|
12
|
|
|
use Closure; |
|
13
|
|
|
|
|
14
|
|
|
class DrawBoxAroundObjects implements Drawable |
|
15
|
|
|
{ |
|
16
|
|
|
private int $boxColor = Color::GREEN; |
|
17
|
|
|
|
|
18
|
|
|
private ?Closure $closure = null; |
|
19
|
|
|
|
|
20
|
|
|
public function __construct( |
|
21
|
|
|
private ObjectLocalizer $objectLocalizer, |
|
22
|
|
|
private Image $image |
|
23
|
|
|
) { |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function boxColor(int $color): static |
|
27
|
|
|
{ |
|
28
|
|
|
$this->boxColor = $color; |
|
29
|
|
|
|
|
30
|
|
|
return $this; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function callback(Closure $closure): static |
|
34
|
|
|
{ |
|
35
|
|
|
$this->closure = $closure; |
|
36
|
|
|
|
|
37
|
|
|
return $this; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function draw(): Image |
|
41
|
|
|
{ |
|
42
|
|
|
$width = $this->image->getWidth(); |
|
43
|
|
|
$height = $this->image->getHeight(); |
|
44
|
|
|
|
|
45
|
|
|
/** @var LocalizedObjectData $obj */ |
|
46
|
|
|
foreach ($this->objectLocalizer->detect() as $obj) { |
|
47
|
|
|
$vertices = $obj->normalizedVertices; |
|
48
|
|
|
|
|
49
|
|
|
if (0 !== count($vertices)) { |
|
50
|
|
|
$x1 = $vertices[0]->x; |
|
51
|
|
|
$y1 = $vertices[0]->y; |
|
52
|
|
|
|
|
53
|
|
|
$x2 = $vertices[2]->x; |
|
54
|
|
|
$y2 = $vertices[2]->y; |
|
55
|
|
|
|
|
56
|
|
|
$this->image->drawRectangle( |
|
57
|
|
|
x1: intval($x1 * $width), |
|
58
|
|
|
y1: intval($y1 * $height), |
|
59
|
|
|
x2: intval($x2 * $width), |
|
60
|
|
|
y2: intval($y2 * $height), |
|
61
|
|
|
color: $this->boxColor, |
|
62
|
|
|
); |
|
63
|
|
|
|
|
64
|
|
|
if ($callback = $this->closure) { |
|
65
|
|
|
$callback($this->image, $obj); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return $this->image; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|