Skip to content

Instantly share code, notes, and snippets.

@ankane
Created August 25, 2022 04:47
Show Gist options
  • Select an option

  • Save ankane/43da41dd67d97039e4a54b0c6c3080a8 to your computer and use it in GitHub Desktop.

Select an option

Save ankane/43da41dd67d97039e4a54b0c6c3080a8 to your computer and use it in GitHub Desktop.

Revisions

  1. ankane created this gist Aug 25, 2022.
    62 changes: 62 additions & 0 deletions detect_objects.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    <?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');