Reputation: 9492
I have this sample image that has white rectangular box with a single black square in it. (2 blue arrows are just for illustration purpose, they are not part of the image)
Is there anyway to find out how many pixels is the black square away from the left and top boundaries of the image?
If possible, i prefer not to use OpenCV
as the rest of the processing were done in PIL
and it's probably an overkill if i have to use OpenCV
just to do this one operation.
FYI: the image is in JPEG, there will always be only 1 black squre (no multiple squares) in the box.
UPDATE
Based on the answer by karlphillip, i have come up with this piece of code.
from PIL import Image
img = Image.open('test.png').convert('1')
pixels = img.load()
xlist = []
ylist = []
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixels[x, y] == 0:
xlist.append(x)
ylist.append(y)
#4 corners of the black square
xleft = min(xlist)
xright = max(xlist)
ytop = min(ylist)
ybot = max(ylist)
Upvotes: 2
Views: 5309
Reputation: 93410
Based on that link I mentioned, I was able to put together the following pseudocode:
from PIL import Image
img = Image.open('test.png')
pixels = img.load()
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixels[x, y] == (0, 0, 0):
// black pixel found, add it to a counter variable or something.
This answer demonstrates how to access and test each pixel in the image using PIL.
Upvotes: 1