I need to find a particular pixel of an image. Let’s say “89 21 24”.
I’m using two nested cycles to walk the image:
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;
}
}
I’d like to have a faster algorithm by increasing $y and $x not one by one, instead for example 4 by 4. (Sixteen times faster?)
Of course I need to know exactly the pixels that build 4×4 square.
I would do it like:
if ($pixel == "" and nextpixel...) {
$px = $x - 1; $py = $y -...;
}
//etc.
Is there a smarter way to achieve that?
EDIT:
Here’s the getpixelat function:
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;
}
If you know that the color you are looking for always appears in patches of at least 2×2, or 3×3, or any fixed size, then yes, you can speed up the lookup by incrementing
$xand$yby more than one at each iteration.For instance, if you know that your patches are always of size at least
KxL, you can do the following: