2012-02-16 46 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. 
     } 
    } 
}