gary.info

here be dragons

detect objects with php

detect_objects.php
<?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');