OpenCV imread transparency gone

Question:

I have an image (a captcha) that I download from the web.

Initial Image

When I loaded to opencv it seems to loose its properties or simply mixes the transparent background with the dark/black colors:

Processed Image

Currently the code does nothing but loading a writing again:

captchaImg = cv2.imread('captcha1.png')
cv2.imwrite("captcha2.png", captchaImg)

I have tried loading also with options 0, 1, 2, 3 but the result is the same.

Asked By: roccolocko

||

Answers:

Well this is a problem with opencv and it has a solution with opencv but it is kind of complex so I went on and use another libary (PIL) that I was going to use any way.
Basically what you do is put a white image behind the transparent one an with that you solve the problem.
The code is the following:

image = Image.open("captcha1.png")
image.convert("RGBA")
canvas = Image.new('RGBA', image.size, (255,255,255,255)) # Empty canvas colour (r,g,b,a)
canvas.paste(image, mask=image) # Paste the image onto the canvas, using it's alpha channel as mask
canvas.save("captcha1.png", format="PNG")

I hope it helps someone with the same problem.

Answered By: roccolocko

Using the provided constants might help. I do the equivalent of

captchaImg = cv2.imread('captcha1.png', cv2.IMREAD_UNCHANGED)

which reads the alpha channel (if there is one). The REPL says that cv2.IMREAD_UNCHANGED is -1

Answered By: Dave W. Smith