|
| 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/multitask.png'); |
| 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 | +$fontSize = 10; |
| 42 | +$fontScalingFactor = 0.75; |
| 43 | +$fontFile = '/Users/Kyrian/Library/Fonts/JosefinSans-Bold.ttf'; |
| 44 | +$labelBoxHeight = $fontSize * 2 * $fontScalingFactor; |
| 45 | +$colors = array_map(fn () => sprintf('#%06x', mt_rand(0, 0xFFFFFF)), range(0, count($boxes) - 1)); |
| 46 | + |
| 47 | +foreach ($boxes as $box) { |
| 48 | + $detectionLabel = $box['label'].' '.round($box['score'], 2); |
| 49 | + $color = $colors[array_search($box, $boxes)]; |
| 50 | + |
| 51 | + $image = $image |
| 52 | + ->drawRectangle($box['xmin'], $box['ymin'], $box['xmax'], $box['ymax'], $color, thickness: 2) |
| 53 | + ->drawRectangle( |
| 54 | + xMin: $box['xmin'], |
| 55 | + yMin: max($box['ymin'] - $labelBoxHeight, 0), |
| 56 | + xMax: $box['xmin'] + (strlen($detectionLabel) * $fontSize * $fontScalingFactor), |
| 57 | + yMax: max($box['ymin'], $labelBoxHeight), |
| 58 | + color: $color, |
| 59 | + fill: true, |
| 60 | + thickness: 2 |
| 61 | + ) |
| 62 | + ->drawText( |
| 63 | + text: $detectionLabel, |
| 64 | + xPos: $box['xmin'] + 5, |
| 65 | + yPos: max($box['ymin'] - $labelBoxHeight, 0), |
| 66 | + fontFile: $fontFile, |
| 67 | + fontSize: $fontSize, |
| 68 | + color: 'FFFFFF' |
| 69 | + ); |
| 70 | +} |
| 71 | + |
| 72 | +$image->save(__DIR__.'/../images/corgi-detected.jpg'); |
0 commit comments