我需要找到图像的特定像素。让我们说"89 21 24"。
我使用两个嵌套循环来遍历图像:
for( $y=$inity; $y<$h; $y++) {
for( $x=$initx; $x<$w; $x++) {
$pixel = getpixelat($img,$x,$y);
if ($pixel == "892124" and getpixelat($img,$x+1,$y) == "1212224") {
$px = $x; $py = $y;
break 2;
}
}
我想要一个更快的算法,不是一个接一个地增加$y和$x,而是例如4乘以4。(快16倍?)当然,我需要确切地知道构建4x4正方形的像素。
我会这样做:
if ($pixel == "" and nextpixel...) {
$px = $x - 1; $py = $y -...;
}
//etc.
有没有更聪明的方法来实现这一点?
编辑:
这是getpixelat函数:
function getpixelat($img,$x,$y) {
$rgb = imagecolorat($img,$x,$y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
return $r.$g.$b;
}
如果您知道要查找的颜色总是出现在至少2x2、3x3或任何固定大小的补丁中,那么是的,您可以通过在每次迭代中将$x
和$y
增加一个以上来加快查找速度。
例如,如果您知道补丁的大小始终至少为KxL
,则可以执行以下操作:
for( $y=$inity; $y<$h; $y += L) {
for( $x=$initx; $x<$w; $x += K) {
$pixel = getpixelat($img,$x,$y);
if ($pixel == "892124" and getpixelat($img,$x+1,$y) == "1212224") {
$px = $x; $py = $y;
break 2;
}
}
}
1.)避免嵌套循环:
2.)保存像素的旧值(调用函数没有那么快)
3.)不要将颜色转换为字符串/不要比较字符串!(什么是1212224?它不是十六进制颜色)
$px=-1;
$py=-1;
$lineW = ($w-$initx);
$lineH = ($h-$inity);
$count = $lineW * $lineH;
$color1 =hexdec ("892124") ;
$color2 =hexdec ("1212224") ;
$x=$initx;
$y=$inity;
$new = imagecolorat($img,$x,$y);
while(true) {
$x++;
if ($x>=$w) {
$x=$initx+1;
$y++;
if ($y>=$h) break;
$new = imagecolorat($img,$x-1,$y);
}
$old = $new;
$new = imagecolorat($img,$x,$y);
if ($old == $color1 && $new == $color2)
{
$px = $x; $py = $y;
break;
}
}
(代码未测试:-)