Jean-Philippe Encausse
Jean-Philippe Encausse

Reputation: 1521

Convert a RGBA bytearray into a cv2 image (no errors, cv2 hang forever)

I receive from websocket an array of [r, g, b, a ... r, g, b, a] representing a 300x300 image

img = np.asarray( bytearray(data), dtype=np.uint8 ).reshape( 300, 300, 4 )

I convert this image using numpy and get an array of array [[r,g,b,a],[r,g,b,a],[r,g,b,a]]

I want to convert that npArray into a cv2 image. I try everything but nothing work. The code hang without errors ...

img = cv2.imread(img, cv2.IMREAD_UNCHANGED)
cv2.imshow('frame', img)

I don't understand what I should do and/or it hangs for any other reason...

Upvotes: 0

Views: 647

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207455

The short answer is that you don't need to.

When you use cv2.imread() it reads and decodes a JPEG-encoded, or PNG-encoded image (or TIFF or other) from disk. It does decoding of compressed images. Your image is not compressed so you don't need that.

Internally, OpenCV stores images as Numpy arrays - you already have that, so your array is already an image. Happy days! You don't need to do anything, this is enough:

img = np.asarray( bytearray(data), dtype=np.uint8 ).reshape( 300, 300, 4 )

Note that np.asarray() shares its data with the bytearray so you may have trouble altering the image. If so, you can make your own modifiable copy with:

img = np.array(... as above ...)

Note also that cv2.imshow() requires a waitKey() afterwards to update the display:

cv2.imshow("Window Title", image)
cv2.waitKey(-1)

Upvotes: 1

Related Questions