Reduce opacity of image using Opencv in Python

Deadly 提交于 2019-12-23 01:32:09

问题


In the program given below I am adding alpha channel to a 3 channel image to control its opacity. But no matter what value of alpha channel I give there is no effect on image! Anyone could explain me why?

import numpy as np
import cv2

image = cv2.imread('image.jpg')
print image

b_channel,g_channel,r_channel = cv2.split(image)
a_channel = np.ones(b_channel.shape, dtype=b_channel.dtype)*10
image = cv2.merge((b_channel,g_channel,r_channel,a_channel))

print image
cv2.imshow('img',image)
cv2.waitKey(0)
cv2.destroyAllWindows()

I can see in the terminal that alpha channel is added and its value changes as I change it in the program, but there is no effect on the opacity of the image itself!

I am new to OpenCV so I might be missing something simple. Thanks for help!


回答1:


Alpha is a channel that is used to control the opacity of an image. An alpha channel typically doesn't do anything unless you perform an action on it. It doesn't make an image transparent on its own.

Alpha is usually used to either remove unimportant areas of an image or to combine one image with another image. In the first case the image is usually simply multiplied by its alpha. This is sometimes referred to premultiplying. In this case the dark areas of the alpha channel darken the RGB and the bright areas leave the RGB untouched.

R = R*A 
G = G*A 
B = B*A

Here is a version of your code that might do what you want (Note- I converted to 32-bit because it's easier to use alpha channels when they are ranged from 0 to 1):

import numpy as np
import cv2

i = cv2.imread('image.jpg')
img = np.array(i, dtype=np.float)
img /= 255.0
cv2.imshow('img',img)
cv2.waitKey(0)

#pre-multiplication
a_channel = np.ones(img.shape, dtype=np.float)/2.0
image = img*a_channel

cv2.imshow('img',image)
cv2.waitKey(0)
cv2.destroyAllWindows()

The second case is used when trying to overlay an image over another image. This is a compositing operation that is often referred to as an "over" merge or a "blend" merge. In this case there is a foreground image "A" and a background image "B" and an alpha channel which could be included in the RGB images or on its own. In this case you can place A over B using:

output = (A * alpha) + (B * (1-alpha))



回答2:


Actually, the answer is simple. OpenCV's imshow() function ignores the alpha channel.

If you want to see the effect of your alpha channel, save your image in PNG format (because that supports alpha channel) and display in a different viewer.

I also wrote a decorator/enhancement for imshow() here that helps visualise transparent images.



来源:https://stackoverflow.com/questions/44320567/reduce-opacity-of-image-using-opencv-in-python

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