slomil - 24 days ago 9
Python Question

# Simple python code with image processing not working

I am working with pixels and I want to find location of first black pixel in picture below when traversing in row-major order. This is a part of project to recognize mnist numbers on image and count sum of all numbers on image.

Code looks like:

``````for a in range(0,80):
for b in range(0,80):
if (imgt[a,b,0]==0 and imgt[a,b,1]==0 and imgt[a,b,2]==0):
x=a
y=b
break
break
break

print x,y
``````

Explaination:- I have two for loops going through coordinates(picture is 80x80,so
`range`
is (0,80)). In for loop, I am checking if pixel is black=>if it is black,
`x`
is assigned coordinate value of
`a`
,
`y`
is
`b`
.

Expected Output:- The program should finally write coordinates of first upperleft black pixel, which should be (29,27).

Actual Output:- The prints me always (56,27).
Does anyone know what can be problem here? It seems to me very simple, but i don't know what to do.

Thanks in advance!

Answer

The problem arose from use of multiple break statements. Moving the code to a separate function and use of return instead of break statements solves it.

``````def glteme():
for a in range(0,80):
for b in range(0,80):
if (imgt[a,b,0]==0 and imgt[a,b,1]==0 and imgt[a,b,2]==0):
return a,b

blackPixelCoordinate = glteme()
print blackPixelCoordinate[0], blackPixelCoordinate[1]
``````
Comments