python OpenCV - add alpha channel to RGB image

前端 未结 4 1414
闹比i
闹比i 2020-11-27 17:22

What is the best way to convert RGB image to RGBA in python using opencv?

Let\'s say I have one array with shape

(185, 198, 3) - it is RGB

4条回答
  •  醉话见心
    2020-11-27 17:48

    Since OpenCV images are just Numpy arrays, you can do this in one-line, nice and fast with Numpy. So here is the setup code:

    import numpy as np
    
    # We'll synthesise a random image and a separate alpha channel full of 128 - semitransparent
    im    = np.random.randint(0,256,(480,640,3), dtype=np.uint8)
    alpha = np.full((480,640), 128, dtype=np.uint8)
    

    And here is the solution which is simply to stack the alpha channel onto the image in the "depth" axis, hence dstack():

    result = np.dstack((im, alpha))
    

提交回复
热议问题