Scanning through pixels vertically first, then across the width

Instead of running the for loop through each pixel, like below.

for i in range(len(pixels)): 
    if pixels[i] = 50 

I want to keep the column the same but jump rows; going down the image to analyze pixel from top to bottom first, then across the row. The purpose is to find the closet pixel from the left side of the image with a given value.

Here’s my code.

width = imp.width; 
height = imp.height; 

for i in range(width): 
	for j in range(height-1):
		if pixels[((width+1)*j)+i] > 10: 
			pix = ((width+1)*j)+i; 

this doesn’t work. Any help.

Hello Iet -

There are two problems with your code:

First, your “+1”. “-1” on the index arithmetic is incorrect.*

Second, you have two nested loops, and your break only breaks
out of the innermost loop.**

Here is code that works:

width = 10
height = 20

pixels = range (width * height)

for i in range (width):
    for j in range (height):
        pix = width * j + i
        print 'pixel =', pixels[pix]
        if pixels[pix] > 10:
    if pixels[pix] > 10:

print 'i =', i, ', j =', j
print 'pix =', pix

(I’ve added a couple of print statements to help make clear
what is going on.)

*) One way to see this is to note that for my values of
width = 10 and height = 20 , the maximum allowable
value for the index into the pixels array is 199, but your
pixel-index expression, pix = ((width+1)*j)+i , takes on
a maximum value of 207 when i = 9 and j = 18, larger
than the allowable 199.

**) I’ve simply added a second break statement to break
out of the outer loop that duplicates the test condition of the
inner break statement. This is perhaps not the most elegant
approach, but it gets the job done and makes clear what is
going on.

Thanks, mm

thank you, it works great. Is it possible to use a reduce function to do the same operation?

def farleft(pixel): 
	 if pixel%width > (pixel+1)%width: 
	 	if pixel  >  1:
	 		return pixel
reduce(farleft, pixels)

returns - TypeError: farleft() takes exactly 1 argument (2 given)

I think reduce might be faster than a for loop? What do you think?