我有一个函数,给定一个具有透明背景和未知对象的图像,找到对象的顶部,左侧,右侧和底部边界。目的是让我可以在对象的边界周围画一个盒子。我不是想要检测物体的实际边缘 - 只是最上方,最下方等。如何优化此图像“边缘检测”算法?
我的功能运行良好,但速度很慢,因为它扫描图像中的每个像素。
我的问题是:是否有一种更快,更有效的方法来检测图像中使用库存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;
}
一些非常有趣的答案,值得一些适当的测试。我会在第二天左右做一些基准测试,并接受性能最好的测试。 – mmatos