How to properly create an blank colored image in numpy (RGBA)

Viewed 407

I am trying to create a blank, colored Image in Numpy that includes an alpha channel (RGBA).

In my quest to find out how to do this, I came to this SO answer. However, when I run either example of the SO answer, the red appears blue, unlike the images shown in the answer.

So, I am wondering what the correct way to do this is as uint16 (instead of uint8) and without the color mix-up? Is this a bug with Numpy or am I doing something wrong?

My resulting image: https://i.ibb.co/VVxhDwY/img.png

My code:

import cv2
import numpy as np

size = (128, 256)

blank_image = np.zeros((size[0], size[1], 4), np.uint8)

# Make first 10 rows red and opaque
blank_image[:10] = [255,0,0,255]

# Make first 10 columns green and opaque
blank_image[:,:10] = [0,255,0,255]

cv2.imwrite('test.png', blank_image)

2 Answers

If instead of cv2 you use matplotlib.pyplot, your code runs perfectly fine (see below) and then you can simply store it with this library already.

Example of your code

The answer you link to was using PIL/Pillow (which uses conventional RGB ordering) rather than OpenCV (which uses BGR ordering). If you want a semi-transparent solid red in 16-bit with OpenCV, use:

#!/usr/bin/env python3

import cv2
import numpy as np

size = (128, 256)

# Make semi-transparent solid red image
im = np.zeros((*size, 4), np.uint16) + [0,0,65535,128]

# Save to disk
cv2.imwrite('result.png', im)

enter image description here

Related