Load python list as opencv image

Viewed 320

I have a 2D python list named image, the array contain only integer in the range from 0-255. For example, the list is like this

image = [[0, 39, 57], [255, 182, 124], [19, 223, 200], [176, 190, 100]]

I have read How to convert a python numpy array to an RGB image with Opencv 2.4?, so i converted the python list to numpy array

image = np.asarray(image)

I could run the following

cv2.imwrite('image.jpg', image)

But how do i load the array as image directly without saving it to file ? something like this

opencvImage = cv2.imread(image, 0)

The above code obviously don't work, so how do i load python list or numpy array directly to opencv without saving it as file? the expected image output is rgb image or greyscale image, and the expected shape is the shape of the list/array itself.

The following code also don't work, i also don't understand why i can save the numpy array as image file but opencv cannot show it directly

cv2.imshow("image", image)

The code above throws assertionfailed error from opencv

2 Answers

Based on the provided information, the only possible output is a gray image with the shape (4, 3). OpenCV image are just basic Numpy arrays. You can convert the list using:

lst = [[0, 39, 57], [255, 182, 124], [19, 223, 200], [176, 190, 100]]
image = np.asarray(lst, dtype=np.uint8) # Specifying dtype is critical here

# image = array([[  0,  39,  57],
#                [255, 182, 124],
#                [ 19, 223, 200],
#                [176, 190, 100]])

Then you can show it with cv2.imshow("image", image) but be aware that the image is a bit too small to be easily seen. Note also that a cv2.waitKey() loop may be needed so the window does not freeze and print the image correctly.

You can crease numpy.array then divide by 255.0 then show the image with cv2 like below:

import numpy as np
import cv2

image = [[0, 39, 57], [255, 182, 124], [19, 223, 200], [176, 190, 100]]
image = np.array(image, copy=False) / 255.0

cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Or you can use matplotlib for showing the image like below:

import matplotlib.pyplot as plt
import numpy as np

image = [[0, 39, 57], [255, 182, 124], [19, 223, 200], [176, 190, 100]]
image = np.array(image, copy=False) / 255.0

plt.imshow(image); plt.axis('off')
plt.show()

Output:

enter image description here

Related