nazeeroo bu
nazeeroo bu

Reputation: 177

Double iteration to a list python 3

for x in range(0,img_row):
    for y in range(0,img_col):
       img_lst.append([img[x,y][0],img[x,y][1],img[x,y][2]])
return img_lst

How do I use list Comprehension here?

img_lst = [img[x,y][0], img[x,y][1], img[x,y][2] y for y in range(0,img_col) for x in range(0, img_row)]

I tried this but it is giving my invalid syntax and when I remove "y" in the beginning it gives me that Y is not defined

the whole function:

def cvimg_to_list(img):
    img_row = img.shape[0]
    img_col = img.shape[1]
    img_lst=[]

    img_lst = [img[x,y][0], img[x,y][1], img[x,y][2] y for y in range(0,img_col) for x in range(0, img_row)]
    return img_lst

Upvotes: 1

Views: 326

Answers (2)

Hirabayashi Taro
Hirabayashi Taro

Reputation: 943

I'm not totally sure about what are you trying to achieve, but if my assumption is correct (you want to get a list of pixel values values from the three channels of an image that you opened with opencv), you can use numpy to do this.

img_lst=img.reshape(-1,3).tolist()

Bearing in mind that cv2 loads images as BGR and not RGB.

note: not being properly an answer to the question, I would have rather post this as a comment but I don't have enough reputation for that

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122262

To convert nested loops with a list.append() call to a list comprehension, all you have to do is move everything between the .append(...) parentheses to the front, remove the : colons after the for loops, and finally add [...] around the result:

[
[img[x,y][0],img[x,y][1],img[x,y][2]]
for x in range(0,img_row)
    for y in range(0,img_col)
]

Note that the order of the for loops does not change!

This can then be put onto one line; I added some whitespace for readability and simplified the range() calls:

[[img[x, y][0], img[x, y][1], img[x, y][2]]
 for x in range(img_row) for y in range(img_col)]

Because you build a new list with the first 3 values from img[x, y], you can also use slicing:

[img[x, y][:3] for x in range(img_row) for y in range(img_col)]

You made three mistakes in your attempt; you swapped the order of the for loops, you added in an extra, stray y, and you dropped the ] closing bracket for the list object you produce each iteration.

Upvotes: 4

Related Questions