Search code examples
pythonarraysnumpyopencvtransparency

Numpy create an empty alpha image


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)

Solution

  • 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]
    

    enter image description here


    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)
    

    enter image description here

    # Make a gradient alpha channel, left-to-right, 0..255
    alpha = np.repeat(np.arange(256,dtype=np.uint8)[np.newaxis,:], 128, axis=0)
    

    enter image description here

    # Apply alpha to RGB image to yield RGBA image
    RGBA = np.dstack((RGB,alpha))
    

    enter image description here