kdodie/img-items

在图像内找到单个项目并获取其大小/坐标。

v0.2.0 2021-09-07 14:55 UTC

This package is auto-updated.

Last update: 2024-09-06 23:52:25 UTC


README

packagist package version packagist package downloads license

在图像内找到单个项目并获取其大小/坐标。这是基于 img-items Node 模块的 PHP 版本。

示例

<?php
require_once('vendor/autoload.php');

$contents = file_get_contents('assets/feed-example.png');
$img = imagecreatefromstring($contents);
$items = img_items($img);

foreach($items as $item) {
  for ($y = $item['top']; $y < $item['bottom'] + 1; $y++) {
    for ($x = $item['left']; $x < $item['right'] + 1; $x++) {
      imagesetpixel($img, $x, $y, imagecolorallocate($img, 255, 0, 0));
    }
  }
}

imagepng($img, 'assets/feed-example-filled.png', 0);
imagedestroy($img);
?>

注意事项

图像越大,或定义的背景颜色越多,该模块运行越慢。可能有一些事情可以提高其效率,但它目前是可行的。

安装

composer require kodie/img-items

用法

img_items(image, options)

<?php
require_once('vendor/autoload.php');

$items = img_items('my-image.jpg', array(
  'background'           => 0,
  'background_threshold' => 5,
  'gap_threshold'        => 5,
  'size_threshold'       => 5
));
?>

参数

$image

要扫描项目的图像。接受图像的文件路径、gd 图像资源GdImage 实例

$options

一个数组,您可以根据需要设置选项以调整项目的查找方式

  • background (默认: 0) - 应该被认为是图像背景的颜色。接受任何字符串,其中包含颜色值,该颜色组件工厂可以将其转换为颜色(示例:#FFFFFFrgb(255, 0, 0)hsl(240, 100%, 50%)),这些颜色字符串的数组,整数设置为 0 以使用右上角像素颜色,整数设置为 -1 以根据图像的平均亮度将背景颜色设置为黑色或白色,或从 110 的整数以使用图像中的主颜色数量。 (请注意,这里定义的颜色越多,模块运行越慢。)

  • background_threshold (默认: 5) - 从 0100 的整数,定义颜色可以多接近背景颜色(使用 CIE76 颜色差异公式),才能被认为是背景的一部分。0 表示完全匹配。

  • gap_threshold (默认: 5) - 定义多少像素的背景颜色之前,项目被视为自己的项目。

  • gap_y_threshold (默认: null) - 与 gap_threshold 相同,但仅在 Y 轴上。(设置为 null 将回退到 gap_threshold

  • gap_x_threshold (默认: null) - 与 gap_threshold 相同,但仅在 X 轴上。(设置为 null 将回退到 gap_threshold

  • size_threshold (默认: 5) - 定义项目应有多宽多高才能被选中。如果项目的宽度或高度低于此值,则将其从结果中过滤掉。

  • height_threshold (默认: null) - 与 size_threshold 相同,但仅适用于项目的高度。(设置为 null 将回退到 size_threshold

  • width_threshold (默认: null) - 与 size_threshold 相同,但仅适用于项目的宽度。(设置为 null 将回退到 size_threshold

示例响应

Array
(
  [0] => Array
    (
      [left] => 728
      [top] => 42
      [right] => 782
      [bottom] => 62
      [width] => 55
      [height] => 21
    )
  [1] => Array
    (
      [left] => 47
      [top] => 44
      [right] => 58
      [bottom] => 61
      [width] => 12
      [height] => 18
    )
  [2] => Array
    (
      [left] => 66
      [top] => 44
      [right] => 93
      [bottom] => 61
      [width] => 28
      [height] => 18
    )
)

相关

  • img-items - 该模块基于的 Node 模块。

许可

麻省理工学院。更多信息请参阅 license.md 文件