Skip to content

Commit f3865ee

Browse files
feat: new example for custom usage for object detection
1 parent 7abc0d9 commit f3865ee

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Codewithkyrian\Transformers\Pipelines;
6+
7+
use Codewithkyrian\Transformers\Models\Auto\AutoModel;
8+
use Codewithkyrian\Transformers\Processors\AutoProcessor;
9+
use Codewithkyrian\Transformers\Utils\Image;
10+
11+
require_once './bootstrap.php';
12+
13+
ini_set('memory_limit', '-1');
14+
15+
$processor = AutoProcessor::fromPretrained('Xenova/yolov9-c_all');
16+
$model = AutoModel::fromPretrained('Xenova/yolov9-c_all');
17+
18+
$image = Image::read(__DIR__.'/../images/corgi.jpg');
19+
20+
$inputs = $processor($image);
21+
22+
['outputs' => $outputs] = $model($inputs);
23+
24+
$boxes = array_map(function ($args) use ($inputs, $model): ?array {
25+
[$xmin, $ymin, $xmax, $ymax, $score, $id] = $args;
26+
27+
if ($score < 0.11) return null;
28+
29+
return [
30+
'xmin' => $xmin,
31+
'ymin' => $ymin,
32+
'xmax' => $xmax,
33+
'ymax' => $ymax,
34+
'score' => $score,
35+
'label' => $model->config['id2label'][$id] ?? 'unknown',
36+
];
37+
}, $outputs->toArray());
38+
39+
$boxes = array_filter($boxes);
40+
41+
foreach ($boxes as $box) {
42+
$image->drawRectangle(
43+
xMin: (int)$box['xmin'],
44+
yMin: (int)$box['ymin'],
45+
xMax: (int)$box['xmax'],
46+
yMax: (int)$box['ymax'],
47+
color: '0099FF',
48+
thickness: 2
49+
);
50+
$image->drawText(
51+
text: $box['label'],
52+
xPos: (int)$box['xmin'],
53+
yPos: (int)max($box['ymin'] - 5, 0),
54+
fontFile: '/Users/Kyrian/Library/Fonts/JosefinSans-Bold.ttf',
55+
fontSize: 14,
56+
color: '0099FF'
57+
);
58+
}
59+
60+
$image->save(__DIR__.'/../images/corgi-detected.jpg');

0 commit comments

Comments
 (0)