William Smith
William Smith

Reputation: 99

Why won't OpenCV show an image stored in a numpy array? (Python)

I read in an image using cv2.imread to a variable and use cv2.imshow to display it just fine. I take the same variable and pass it into a numpy array of the same shape as the image and try to display it. Same shape, same data type and same values in the array and I get a blank, white square from cv2.imshow. Why not the image?

If I take the numpy array and save it using cv2.imwrite it saves the picture just fine. Any help appreciated, this has been driving me crazy.

images = np.zeros(shape=(1,30,30,3))

i = 1
a = cv2.resize(cv2.imread('/media/images/'+str(i)+'.png', 1), (30,30))

b = images[0] = a

print(b.shape, images[0].shape)
print(type(b), type(images[0]))

# Displays image
cv2.imshow('img', b)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Displays blank, white image
cv2.imshow('img', images[0])
cv2.waitKey(0)
cv2.destroyAllWindows()

Upvotes: 1

Views: 5446

Answers (1)

Demi-Lune
Demi-Lune

Reputation: 1967

b and images don't have the same dtype:

>>> images[0].dtype
dtype('float64')
>>> b.dtype
dtype('uint8')

So cv2 doesn't know how to color images.

So if your first line is:

images = np.zeros(shape=(1,30,30,3), dtype=np.uint8)

it should fix the problem.

Upvotes: 3

Related Questions