cv2 imread transparency gone

牧云@^-^@ 提交于 2021-02-10 12:18:06

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/45623312/cv2-imread-transparency-gone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!