0

I have a stream of images coming in from a source which is, unfortunately a list of list of tuples of RGB values. I want to perform real-time processing on the image, but that code expects a Numpy array of shape (X,Y,3) where X and Y are the image height and width.

X = [[(R, G, B)...]]
img_arr = np.array([*X])

The above works fine but takes nearly a quarter of a second with my images which is obviously too slow. Interestingly, I also need to go back the other direction after the processing is done, and that code (which seems to work) is not so slow:

imgout = map(tuple, flipped_image)

Some relevant other questions:

why is converting a long 2D list to numpy array so slow?

Convert List of List of Tuples Into 2d Numpy Array

Cole H
  • 3
  • 1
  • Did you check what `imgout` is? Is it really a list of tuples? or just a `map` object? For the original conversion what does `np.array(X)` do? – hpaulj Jan 28 '22 at 01:21
  • 1
    `imgout = map(tuple, flipped_image)` seems fast because it's not actually doing what you want. – user2357112 Jan 28 '22 at 01:23

1 Answers1

1

To answer the title of your question, numpy automatically lists and tuples to numpy arrays, so you can just use np.array(X), which will be about as fast as you can get:

img_arr = np.array(X)

A simple list comprehension will convert it back to the list-list-tuple form:

imgout = [[tuple(Z) for Z in Y] for Y in img_arr]

Code to generate a sample 10x10 X array:

X = [[tuple(Z) for Z in Y] for Y in np.random.randint(0,255,(10,10,3))]