[英]Converting image grayscale pixel values to alpha values
是否可以使用 OpenCV、Pillow 和 scikit-image 等库在 python 中将图像灰度像素值转换为 alpha 值?
这是一个使用 OpenCV 的测试程序:
path = "e:/python/sampleImage.tif"
src = cv2.imread(path, -1)
print("shape: ",src.shape)
print("co_pixel value3: ",src[970,1000])
cv2.imshow("Displaying only blue channels",src)
cv2.waitKey(0)
cv2.destroyAllWindows()
尝试将您的灰度图像转换为 BGRA。 然后将灰色图像复制为 alpha。 然后将 alpha 图像放入 3 通道(BGR)灰度图像的 alpha 通道中。
alpha = src.copy()
src = cv2.cvtColor(src, cv2.COLOR_GRAY2BGRA)
src[:,:,3] = alpha
具有 alpha 通道的图像只是具有 4 个通道的图像:3 种颜色(OpenCV 中的 B、G、R)和 alpha 通道。 所以假设你有你的彩色图像src
。 然后
import numpy as np
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
img_w_alpha = np.dstack( (src, gray) )
np.dstack
将 alpha 通道作为第四个通道添加到您的彩色图像中。
我不明白,为什么你想要这样做,所以如果这不能回答你的问题,也许你需要详细说明。
编辑:按照您的评论,也许您正在寻找 alpha 混合?
import cv2
# Load the tiff
tif = cv2.imread('tmp/Nixon.tif')
h,w,c = tif.shape
alpha = cv2.cvtColor(tif, cv2.COLOR_BGR2GRAY)
tif_a = cv2.cvtColor(tif, cv2.COLOR_BGR2BGRA)
tif_a[:,:,3] = alpha # now you have an image whose alpha channel equals the greyscale values,
# but I'm not sure what good that is
# load a background image
img = cv2.imread('tmp/PA110602.JPG')
img = cv2.resize(img, (w,h)) # for blending, both images need to be of same size
# blend the two images, using the greyscale version of tif as alpha values
blend = cv2.add(
alpha.reshape((*alpha.shape,1))/255.0*tif.astype(float),
(1.0-alpha.reshape((*alpha.shape,1))/255.0)*img.astype(float),
dtype=cv2.CV_8UC1)
如您所见,在尼克松的图像几乎是黑色的地方,例如在他的夹克和头发上,背景图像是可见的,而在尼克松图像明亮的地方,例如他的领子和脸,背景图像几乎不可见。
混合的代码看起来很别扭,因为
h-by-w
与图像h-by-w-by-c
图像,但我们可以乘一个h-by-w-by-1
图像与h-by-w-by-c
图像,因此我们必须使用reshape
将维度添加到alpha
中。但是,如果这是您所追求的,请在谷歌上搜索“阿尔法混合”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.