Reputation: 4444
I use PIL.ImageGrab
to take a screenshot:
screen = ImageGrab.grab(bbox=(869,657,955,714))
screen.save("PictureName.png")
Later, I use cv2.imread
to open that image, and want to get the alpha channel:
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)
That doesn't work, and I get the following error:
alpha = template[:,:,3] -> index 3 is out of bounds for axis 2 with size 3
How can I fix this in order to make this code work?
Upvotes: 0
Views: 720
Reputation: 18925
The actual problem is, that by default PIL.ImageGrab
uses Image
objects with mode RGB
. So, the saved image has no alpha channel. Even when using cv2.imread(..., cv2.IMREAD_UNCHANGED)
, the resulting NumPy array will have shape (height, width, 3)
, such that accessing template[..., 3]
will lead to the given error.
So, there seem to be two options to improve your code in terms of enforcing the alpha channel.
After grabbing the screenshot, convert the Image
object to mode RGBA
, and then save.
When opening the image, check template.shape[2] == 3
, and if necessary, use cv2.cvtColor(template, cv2.COLOR_BGR2BGRA)
.
Here's some code snippet:
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)
That's the output:
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
----------------------------------------
Upvotes: 1