更快地拍摄图像

时间:2012-07-26 13:46:45

标签: php image

我需要找到图像的特定像素。让我们说“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;
}

2 个答案:

答案 0 :(得分:1)

如果你知道你要找的颜色总是出现在至少2x2或3x3或任何固定大小的补丁中,那么是的,你可以通过递增$x和{{1来加速查找每次迭代时不止一次。

例如,如果您知道补丁的大小始终至少为$y,则可以执行以下操作:

KxL

答案 1 :(得分:1)

1。)避免嵌套循环:

2。)保存pixle的旧值(调用函数不是那么快)

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;
  }
}

(代码未经过测试:-))

相关问题