我尝试了下面的代码,它没有显示任何错误并且运行正常,但是更改 alpha channel 的值,并没有显示图像的任何变化
img3 = cv2.cvtColor(img2, cv2.COLOR_BGR2BGRA)
img3[:,:,3] = 100
cv2.imshow('img1',img2)
cv2.imshow('img',img3)
cv2.waitKey(0)
工作正常,但两个图像的输出是相同的,应用 alpha channel 后没有可见的变化
我已经尝试过下面的代码
最佳答案
您的代码实际上是正确的。
简单的答案是 OpenCV 的 imshow()
忽略透明度,因此如果您想查看其效果,请将您的图像保存为 PNG/TIFF(两者都支持透明度)并使用不同的查看器查看它 - 例如 GIMP , Photoshop 或 feh
.
作为替代方案,我为 OpenCV 的 imshow()
制作了一个包装器/装饰器。像 Photoshop 一样显示覆盖在棋盘上的透明图像。所以,从这张 RGBA Paddington 图像和这张 gray+alpha Paddington 图像开始:
#!/usr/bin/env python3
import cv2
import numpy as np
def imshow(title,im):
"""Decorator for OpenCV "imshow()" to handle images with transparency"""
# Check we got np.uint8, 2-channel (grey + alpha) or 4-channel RGBA image
if (im.dtype == np.uint8) and (len(im.shape)==3) and (im.shape[2] in set([2,4])):
# Pick up the alpha channel and delete from original
alpha = im[...,-1]/255.0
im = np.delete(im, -1, -1)
# Promote greyscale image to RGB to make coding simpler
if len(im.shape) == 2:
im = np.stack((im,im,im))
h, w, _ = im.shape
# Make a checkerboard background image same size, dark squares are grey(102), light squares are grey(152)
f = lambda i, j: 102 + 50*((i+j)%2)
bg = np.fromfunction(np.vectorize(f), (16,16)).astype(np.uint8)
# Resize to square same length as longer side (so squares stay square), then trim
if h>w:
longer = h
else:
longer = w
bg = cv2.resize(bg, (longer,longer), interpolation=cv2.INTER_NEAREST)
# Trim to correct size
bg = bg[:h,:w]
# Blend, using result = alpha*overlay + (1-alpha)*background
im = (alpha[...,None] * im + (1.0-alpha[...,None])*bg[...,None]).astype(np.uint8)
cv2.imshow(title,im)
if __name__ == "__main__":
# Open RGBA image
im = cv2.imread('paddington.png',cv2.IMREAD_UNCHANGED)
imshow("Paddington (RGBA)",im)
key = cv2.waitKey(0)
cv2.destroyAllWindows()
# Open Grey + alpha image
im = cv2.imread('paddington-ga.png',cv2.IMREAD_UNCHANGED)
imshow("Paddington (grey + alpha)",im)
key = cv2.waitKey(0)
cv2.destroyAllWindows()
你会得到这个:
还有这个:
关键词 :图像、图像处理、Python、alpha channel 、透明度、叠加、棋盘、棋盘、混合、混合。 OpenCV、imshow、cv2.imshow。
关于python - 如何在 BGR 图像中添加特定值的 Alpha channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58679682/