-2

So I have a numpy array which I convert into a list of tuples like this

orig_img = cv2.imread("plane.jpg")


def cvimg_to_list(img: numpy.ndarray) -> list:
    img_lst = [] 
    img_row = img.shape[0] # Width
    img_column = img.shape[1] # Height

    for x in range(0, img_row): # (Width * Height)
        for y in range(0, img_column): 
            img_lst.append((img[x,y][0],  #B value
                            img[x,y][1],  #G value
                            img[x,y][2])) #R value

    return img_lst

orig_list = cvlib.cvimg_to_list(orig_img)
print(orig_list) #hundreds of thousands of values

>>> [(139, 80, 48), (135, 82, 39), ...] 

Now I want to write a function generator_from_image which takes a image and returns a function which given an index for a pixel returns the color of that pixel.

The functions that are returned should look like the representation for images as one-dimensional lists. The return value for index 0 is the pixel in the upper left corner, the return value for the width of the image is the upper right corner, and so on.

Here's what I tried:

def generator_from_image(img):
    
    def get_color_from_index(x, y):
        color = (x, y) #Need help here...
        return color

    return get_color_from_index(img)
Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
Erik
  • 1
  • 3
  • I don't think you need to have a double Python loop over each pixel in the image to get what you want. You can split the image into R,G,B channels using cv2.split(image) to 3 grayscale images. Then you can flatten each to 1D arrays using np.flatten(). Then you can interweave them using np.ravel(). See https://stackoverflow.com/questions/5347065/interweaving-two-numpy-arrays for interweaving. Then you can use array.tolist to convert the previous result to a list. This should be much faster than what you are doing. – fmw42 Oct 01 '22 at 23:30

1 Answers1

0
  • If what you want is to return the original pixel at (x,y) with generator_from_image taking the list of pixels as input, you will need the original image shape of the image which was (img_row, img_column, 3) for instance:

you can do:

def generator_from_image(img):
    
    def get_color_from_index(x, y):
        color = img[x*img_column + y]
        return color

    return get_color_from_index

What is done here is jumping x times the number of comuns img_column of the original image and adding y to reach the flattened index.

  • Also, instead of looping through img_row and img_column and append the pixels, you can just do: img.reshape((-1, 3)).tolist() to get a list or img.reshape((-1, 3)) to get a numpy array.
PlainRavioli
  • 1,127
  • 1
  • 1
  • 10