我尝试了下面的代码,它没有显示任何错误并且运行正常,但是更改 alpha 通道的值,没有显示图像的任何变化
img3 = cv2.cvtColor(img2, cv2.COLOR_BGR2BGRA)
img3[:,:,3] = 100
cv2.imshow('img1',img2)
cv2.imshow('img',img3)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)
工作正常,但两个图像的输出相同,并且应用 Alpha 通道后没有可见的变化
我已经尝试过下面的代码
你的代码实际上是正确的。
简单的答案是 OpenCVimshow()
忽略透明度,因此如果您想查看其效果,请将图像保存为 PNG/TIFF(两者都支持透明度)并使用不同的查看器(例如GIMP、Photoshop或feh
.
作为替代方案,我为 OpenCV 制作了一个包装器/装饰器imshow()
,它可以像 Photoshop 一样在棋盘上显示具有透明度的图像。因此,从 RGBA 帕丁顿图像和灰色+alpha 帕丁顿图像开始:
#!/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()
Run Code Online (Sandbox Code Playgroud)
你会得到这个:
和这个:
关键词:图像、图像处理、Python、Alpha 通道、透明度、叠加、棋盘、棋盘、混合、混合。OpenCV、imshow、cv2.imshow。