【发布时间】:2014-07-19 14:21:45
【问题描述】:
我有一个函数,给定一个透明背景的图像和一个未知对象,找到对象的顶部、左侧、右侧和底部边界。目的是让我可以简单地在对象的边界周围画一个框。我不是要检测物体的实际边缘——只是最上面、最下面等等。
我的函数运行良好,但速度很慢,因为它扫描图像中的每一个像素。
我的问题是:有没有一种更快、更有效的方法来检测图像中最上方、最左侧、最右侧和最底部的非透明像素,使用现有的 PHP/GD 功能?
有一个影响选项的问题:图像中的对象可能有透明部分。例如,如果它是未填充形状的图像。
public static function getObjectBoundaries($image)
{
// this code looks for the first non white/transparent pixel
// from the top, left, right and bottom
$imageInfo = array();
$imageInfo['width'] = imagesx($image);
$imageInfo['height'] = imagesy($image);
$imageInfo['topBoundary'] = $imageInfo['height'];
$imageInfo['bottomBoundary'] = 0;
$imageInfo['leftBoundary'] = $imageInfo['width'];
$imageInfo['rightBoundary'] = 0;
for ($x = 0; $x <= $imageInfo['width'] - 1; $x++) {
for ($y = 0; $y <= $imageInfo['height'] - 1; $y++) {
$pixelColor = imagecolorat($image, $x, $y);
if ($pixelColor != 2130706432) { // if not white/transparent
$imageInfo['topBoundary'] = min($y, $imageInfo['topBoundary']);
$imageInfo['bottomBoundary'] = max($y, $imageInfo['bottomBoundary']);
$imageInfo['leftBoundary'] = min($x, $imageInfo['leftBoundary']);
$imageInfo['rightBoundary'] = max($x, $imageInfo['rightBoundary']);
}
}
}
return $imageInfo;
}
【问题讨论】:
-
一些非常有趣的答案值得进行适当的测试。我会在第二天左右做一些基准测试,并接受表现最好的。
标签: php image-processing gd edge-detection