Image broke after togray

img = cv2.imread("heads.png")

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

The image broke after togray :frowning:

Original image here.

do you realize that your file has an alpha channel?

please consult docs for imread.

you need to ask for IMREAD_UNCHANGED.

further, cvtColor can’t convert to “grayscale with alpha”. that format isn’t defined.

well, the “designer” at the desk next to you might be an idiot, but you can still “repair” it:


im = cv2.imread("img.png",-1) # load WITH alpha
alpha = im[:,:,3] # extract A
im[alpha==0] = 255 # reset to 'opaque'
i2 = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) # there we go !
1 Like

the file isn’t broken. what you see (backgrounds) is normal behavior for alpha-aware programs.

cvtColor simply doesn’t know how to handle alpha channels.

there is no “grayscale with alpha” format.

if you want to lose all color, you can cvtColor to gray, and then copy that info into the R,G,B channels, keeping the alpha channel. that will look gray, but maintain alpha.

those pixels where alpha == 0 don’t matter at all. those pixels are allowed to have arbitrary color info. it is never actually visible.

the image has 4420000 pixels. 4851 pixels are not totally transparent or totally opaque. those you need to be careful with.