Created
August 25, 2022 04:47
-
-
Save ankane/43da41dd67d97039e4a54b0c6c3080a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once __DIR__ . '/../vendor/autoload.php'; | |
function getPixels($img) | |
{ | |
$pixels = []; | |
$width = imagesx($img); | |
$height = imagesy($img); | |
for ($y = 0; $y < $height; $y++) { | |
$row = []; | |
for ($x = 0; $x < $width; $x++) { | |
$rgb = imagecolorat($img, $x, $y); | |
$color = imagecolorsforindex($img, $rgb); | |
$row[] = [$color['red'], $color['green'], $color['blue']]; | |
} | |
$pixels[] = $row; | |
} | |
return $pixels; | |
} | |
$img = imagecreatefromjpeg('bears.jpg'); | |
$pixels = getPixels($img); | |
$model = new OnnxRuntime\Model('model.onnx'); | |
$result = $model->predict(['inputs' => [$pixels]]); | |
$coco_labels = [ | |
23 => 'bear', | |
88 => 'teddy bear' | |
]; | |
function drawBox(&$img, $label, $box) | |
{ | |
$width = imagesx($img); | |
$height = imagesy($img); | |
$top = round($box[0] * $height); | |
$left = round($box[1] * $width); | |
$bottom = round($box[2] * $height); | |
$right = round($box[3] * $width); | |
// draw box | |
$red = imagecolorallocate($img, 255, 0, 0); | |
imagerectangle($img, $left, $top, $right, $bottom, $red); | |
// draw text | |
$font = '/System/Library/Fonts/HelveticaNeue.ttc'; | |
imagettftext($img, 16, 0, $left, $top - 5, $red, $font, $label); | |
} | |
foreach ($result['num_detections'] as $idx => $n) { | |
for ($i = 0; $i < $n; $i++) { | |
$label = intval($result['detection_classes'][$idx][$i]); | |
$label = $coco_labels[$label] ?? $label; | |
$box = $result['detection_boxes'][$idx][$i]; | |
drawBox($img, $label, $box); | |
} | |
} | |
// save image | |
imagejpeg($img, 'labeled.jpg'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment