I'm trying to identify the width of a colored rectangle inside an image. For the image handling I'm using Imagick for PHP.
The idea was to convert the image into txt and search this txt with a regex for all pixels that have a specific color (#00FF00).
Here is an example of what that txt looks like (excerpt starting at pixel column 0 row 83):
0,83: (255,255,255,1) #FFFFFF graya(255,1)
1,83: (255,255,255,1) #FFFFFF graya(255,1)
2,83: (255,255,255,1) #FFFFFF graya(255,1)
3,83: (0,255,0,1) #00FF00 graya(0,1)
4,83: (0,255,0,1) #00FF00 graya(0,1)
5,83: (0,255,0,1) #00FF00 graya(0,1)
6,83: (255,255,255,1) #FFFFFF graya(255,1)
7,83: (255,255,255,1) #FFFFFF graya(255,1)
8,83: (255,255,255,1) #FFFFFF graya(255,1)
0,84: (255,255,255,1) #FFFFFF graya(255,1)
1,84: (255,255,255,1) #FFFFFF graya(255,1)
2,84: (255,255,255,1) #FFFFFF graya(255,1)
3,84: (0,255,0,1) #00FF00 graya(0,1)
4,84: (0,255,0,1) #00FF00 graya(0,1)
5,84: (0,255,0,1) #00FF00 graya(0,1)
....
Here is my Code:
$canvasImg = new Imagick("_sources/passepartout/". $deviceName .".png");
$canvasImg->setFormat(txt);
preg_match_all("/(\\d+),(\\d+): \\(0,255,0,1\\)/is", $canvasImg, $colorMatchAll);
$firstPixelX = reset($colorMatch[1]);
$lastPixelX = end($colorMatch[1]);
$canvasWidth = $lastPixelX - $firstPixelX;
This works fine so far, but its awfully slow as it finds all pixels in the colored rectangle including the full height of the y axis.
Now as I'm only interested in the width of this #00FF00 rectangle I thought it would be faster if the regex just finds the first pixel that is #00FF00 and then goes through the pixel row until the end (row 83 in my example) and stops as soon as it hits the 84th row.
Is there a modification I could do to my regex that it does what I'm looking for?