问题
I wanted to create a blank alpha image to parse some data from py-opencv and save it on an transparent background png file.
I tried :
blank_image = np.zeros((H,W,4), np.uint8)
and
blank_image = np.full((H, W, 4) , (0, 0, 0, 0), np.uint8)
(H and W are Height and Width)
Both still render a black background instead of a transparent one.
how to get a blank alpha transparent image?
Thanks in advance :)
Edits:
as mentioned by Mark Setchell: you need to specify the alpha channel on other colors involved:
# size of the image
(H , W) = 1080, 1080
# Blank image with RGBA = (0, 0, 0, 0)
blank_image = np.full((H, W, 4), (0, 0, 0, 0), np.uint8)
# Green color with Alpha=255
RGBA_GREEN = (0, 255, 0, 255)
# Opencv element using the RGBA color
cv2.putText(blank_image, 'my opencv element', (20 , 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, RGBA_GREEN, 2)
cv2.imwrite('image_alpha.png', blank_image)
回答1:
You need to make the alpha channel = 255 to see anything.
import numpy as np
H, W = 128, 256
blank_image = np.zeros((H,W,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]
You can also make your RGB image as you wish, then create an alpha layer entirely separately and add it afterwards:
# Make solid red image
RGB = np.full((H, W, 3) , (255, 0, 0), np.uint8)
# Make a gradient alpha channel, left-to-right, 0..255
alpha = np.repeat(np.arange(256,dtype=np.uint8)[np.newaxis,:], 128, axis=0)
# Apply alpha to RGB image to yield RGBA image
RGBA = np.dstack((RGB,alpha))
来源:https://stackoverflow.com/questions/60772938/numpy-create-an-empty-alpha-image