是否可以使用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()
答案 0 :(得分:1)
尝试将灰色图像转换为BGRA。然后将灰色图像复制为Alpha。然后将Alpha图像放入3通道(BGR)灰度图像的Alpha通道中。
alpha = src.copy()
src = cv2.cvtColor(src, cv2.COLOR_GRAY2BGRA)
src[:,:,3] = alpha
答案 1 :(得分:1)
具有alpha通道的图像只是具有4个通道的图像:3种颜色(OpenCV中为B,G,R)和alpha通道。因此,假设您有彩色图像const directions = [
[-1, 0],
[0, 1],
[1, 0],
[0, -1]
];
const exist = (board, word) => {
if (board.length === 0) {
return false;
}
const depthFirstSearch = (row, col, k) => {
if (board[row][col] !== word[k]) {
return false;
}
if (k === word.length - 1) {
return true;
}
board[row][col] = 'VISITED';
for (const [diffRow, diffCol] of directions) {
const nextRow = row + diffRow;
const nextCol = col + diffCol;
if (
nextRow > -1 &&
nextCol >= 0 &&
nextRow < board.length &&
nextCol < board[0].length
) {
if (depthFirstSearch(nextRow, nextCol, k + 1)) {
return true;
}
}
}
board[row][col] = word[k];
return false;
};
for (let row = 0; row < board.length; ++row) {
for (let col = 0; col < board[0].length; ++col) {
if (depthFirstSearch(row, col, 0)) {
return true;
}
}
}
return false;
};
。然后
src
import numpy as np
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
img_w_alpha = np.dstack( (src, gray) )
将Alpha通道作为第四通道添加到您的彩色图像。
尽管我不明白,为什么您想这样做,所以,如果这不能解决您的问题,也许您需要详细说明。
编辑:发表评论后,也许您正在寻找Alpha混合功能?
np.dstack
如您所见,尼克松的图像几乎是黑色的,例如在他的外套和头发中,背景图像是可见的,而尼克松的图像是明亮的,例如他的衣领和脸,几乎看不到背景图像。
混合代码看起来很尴尬,因为
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
使用alpha
。但是,如果您要这样做的话,可以对Google搜索进行“ alpha混合”。