2012-02-16 47 views
0

如何检查PHP中的像素模式?检查像素模式

我的意思是我想用作条件,像素A有xxx值,接下来的像素B有另一个值yyy。

这是我写的:

$img = imagecreatefrompng("myimage.png"); 


$w = imagesx($img); 
$h = imagesy($img); 

for($y=0;$y<$h;$y++) { 
    for($x=0;$x<$w;$x++) { 
     $rgb = imagecolorat($img, $x, $y); 
     $r = ($rgb >> 16) & 0xFF; 
     $g = ($rgb >> 8) & 0xFF; 
     $b = $rgb & 0xFF;   
     echo "#".$r.$g.$b.","; 
     $pixel = $r.$g.$b; 
     if ($pixel == "481023" and $pixel+1??? 
    } 
    echo "<br />\r\n"; 
} 

我想也问我是否可以通过2每递增$ x值的周期,加快了整个事情。这是因为我有2个像素的图案,也许我可以使用类似:

for($x=0;$x<$w;$x+2) { 
    //... 
    if ($pixel == "xxx") {//check the following pixel} 
    else if ($pixel == "yyy") {//check the previous pixel} 
} 
+0

您是否尝试过它每两个像素?你的代码不工作吗? – DampeS8N 2012-02-16 16:28:23

+0

我不知道如何把第一个条件检查2个连续的像素。 – KingBOB 2012-02-16 16:29:39

+0

你想完成什么?你是否正在检查两个图像是否相同/相似?你是否检查图像中的图案或特定序列的存在? – 2012-02-16 16:32:45

回答

0

您可能希望定义一个函数,如:

function getpixelat($img,$x,$y) { 
    $rgb = imagecolorat($img,$x,$y); 
    $r = dechex(($rgb >> 16) & 0xFF); 
    $g = dechex(($rgb >> 8) & 0xFF); 
    $b = dechex($rgb & 0xFF); 
    return $r.$g.$b; 
} 

通知的dechex - 你需要这个,如果你想它看起来像一个HTML颜色代码。否则,“白色”将是255255255而不是ffffff,并且您还会得到模糊的颜色 - 是202020深灰色(20,20,20)或“红色,带有轻微的蓝色提示”(202,0,20)?

一旦你有了这个,它应该是一个简单的事情:

for($y=0; $y<$h; $y++) { 
    for($x=0; $x<$w; $x++) { 
     $pixel = getpixelat($img,$x,$y); 
     if($pixel == "481023" && getpixelat($img,$x+1,$y) == "998877") { 
      // pattern! Do something here. 
      $x++; // increment X so we don't bother checking the next pixel again. 
     } 
    } 
}