0

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!

enter image description here

saurabheights
  • 3,967
  • 2
  • 31
  • 50
slomil
  • 193
  • 1
  • 4
  • 12
  • You are cropping from 0 index in first line. Shouldn't that be (28:56, 28:56) – saurabheights Nov 11 '16 at 19:04
  • I don't understand,you think of this imgtt=imgt[0:28,0:28] ? i just wanted to make some image with dimensions 28x28,i think it can be any interval that contains 28 numbers..? – slomil Nov 11 '16 at 19:12
  • You are right. imgtt is not even used. I just looked at the first line and the image to conclude. My mistake. The problem looks like you are assuming that use of break will get you out of both for loops. break exits only from one outer loop, which is probably why you get first column but last row of the black pixel. – saurabheights Nov 11 '16 at 19:21
  • Try this: http://stackoverflow.com/questions/21293336/python-break-out-of-all-loops. – saurabheights Nov 11 '16 at 19:22
  • Cool I will post it as answer. Best of luck, and you can avoid situation like this if you use debugging. Eclipse seems to have nice support for python. You can add your edited code to my answer. Will be helpful for others. – saurabheights Nov 11 '16 at 19:46
  • Two tips. In your edit, don't call the function twice while printing. Next; Use better names for variables, limit to 2-3 words when naming a variable. This makes code readable by a lot. You can read some good article on python coding conventions. :) – saurabheights Nov 11 '16 at 20:01

1 Answers1

0

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]
saurabheights
  • 3,967
  • 2
  • 31
  • 50