如何在使用PIL.ImageGrab和cv2.imread时强制alpha通道?

2024-05-08 16:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用PIL.ImageGrab截图:

screen = ImageGrab.grab(bbox=(869,657,955,714))
screen.save("PictureName.png")

稍后,我使用cv2.imread打开该图像,并希望获得alpha通道:

template = cv2.imread('PictureName.png', cv2.IMREAD_UNCHANGED)
hh, ww = template.shape[:2]
alpha = template[:,:,3]
alpha = cv2.merge([alpha,alpha,alpha])
cv2.imshow('alpha',alpha)

这不起作用,我得到以下错误:

alpha = template[:,:,3] -> index 3 is out of bounds for axis 2 with size 3

如何修复此问题以使此代码正常工作


Tags: 图像alphapilpngsavetemplatecv2screen
1条回答
网友
1楼 · 发布于 2024-05-08 16:34:52

实际的问题是,默认情况下PIL.ImageGrab使用模式为RGBImage对象。因此,保存的图像没有alpha通道。即使在使用cv2.imread(..., cv2.IMREAD_UNCHANGED)时,生成的NumPy数组也将具有(height, width, 3)形状,因此访问template[..., 3]将导致给定的错误

因此,在执行alpha通道方面,似乎有两种方法可以改进代码

  1. 抓取屏幕截图后,将Image对象转换为模式RGBA,然后保存

  2. 打开映像时,请选中template.shape[2] == 3,如有必要,请使用cv2.cvtColor(template, cv2.COLOR_BGR2BGRA)

下面是一些代码片段:

import cv2
from PIL import ImageGrab

# Force alpha channel in screenshot saving
screen = ImageGrab.grab((0, 0, 200, 200))
screen.save('image_rgb.png')
screen.convert('RGBA').save('image_rgba.png')


# If necessary, add alpha channel after reading the image
def force_alpha_read(filename):
    print('DEBUG:', filename)
    image = cv2.imread(filename, cv2.IMREAD_UNCHANGED)
    if image.shape[2] == 3:
        image = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA)
        print('DEBUG: Added alpha channel')
    return image


template = force_alpha_read('image_rgb.png')
print(template.shape)

template = force_alpha_read('image_rgba.png')
print(template.shape)

这就是输出:

DEBUG: image_rgb.png
DEBUG: Added alpha channel
(200, 200, 4)
DEBUG: image_rgba.png
(200, 200, 4)
                    
System information
                    
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
OpenCV:        4.5.1
Pillow:        8.1.0
                    

相关问题 更多 >