4

I'm trying to figure out what's wrong with my code.

I want to load my image containing the alpha channel and the description from the official website says that:

cv.IMREAD_UNCHANGED: If set, return the loaded image as is (with alpha channel, otherwise it gets cropped).

Here's my try:

import cv2 as cv 

img2 = cv.imread( 'lbj.jpg' , cv.IMREAD_UNCHANGED)

img2.shape

And the result shows : (350, 590, 3)

Isn't it supposed to be (350,590,4)?

Thanks!

My Work
  • 2,143
  • 2
  • 19
  • 47
H_E_A_D
  • 101
  • 1
  • 1
  • 8
  • 3
    Jpeg doesn't have alpha channel – Miki Sep 11 '18 at 06:58
  • @Miki So if I want to modify the value of alpha channel in this picture,how can i achieve it? Thanks – H_E_A_D Sep 11 '18 at 07:00
  • How are you going to modify the alpha channel? You want a consistent alpha channel across whole image or selectively change alpha for some regions of image ? – ZdaR Sep 11 '18 at 07:04
  • @ZdaR maybe just want to make the picture looks more transparent?And by the way ,I make it png but still shows only three channels..What's wrong with it? Thanks! – H_E_A_D Sep 11 '18 at 07:11
  • What is the source of this `.png` file are you writing it by yourself, or you are getting it from somewhere else ? – ZdaR Sep 11 '18 at 07:21
  • @ZdaR i downloaded from the website i think it needs to be saved as a 24bit and i don't know what bit would it be if i just pick a picture from web maybe can you show me how to check or even how to change it to 24bit? Thanks – H_E_A_D Sep 11 '18 at 07:27
  • You can either load that image to GIMP or Photoshop to check if alpha is present, but in case of 24 bit it has to be RGB only, without alpha, since each channel consumes 8 bits, so RGBA images are 32 bit. – ZdaR Sep 11 '18 at 07:34
  • @ZdaR So what you mean is that normally ,the picture with RGBA would be 32 bit since RGB have 24bit and alpha has 8bit? And we need to maybe "convert" it to 24bit? Thanks! – H_E_A_D Sep 11 '18 at 07:40

1 Answers1

9

The reason there are only three channels is that the image is in jpg format, which does not have an alpha channel. If you were to load e.g. a png format image which had an alpha channel then

img2 = cv.imread( 'lbj.png' , cv.IMREAD_UNCHANGED)

with 'lbj.png' would load the image with the alpha channel included, and then

img2.shape

would show (350, 590, 4).

If you convert a jpg to png then you will still, at that point, have only three channels because the image would only have the BGR channels that were in the original jpg. However, you could at this point add an alpha channel to make it BGRA and then proceed to work with transparency options.

Adding an alpha channel is answered in python-opencv-add-alpha-channel-to-rgb-image

Mick
  • 811
  • 14
  • 31