Python 3.x 从屏幕抓取图像到numpy阵列,并将其显示为黑白图像
我试图从屏幕的某个部分读取图像数据,以便以Python 3.x 从屏幕抓取图像到numpy阵列,并将其显示为黑白图像,python-3.x,numpy,python-imaging-library,Python 3.x,Numpy,Python Imaging Library,我试图从屏幕的某个部分读取图像数据,以便以numpy数组的形式对其进行后期处理。这就是我迄今为止所尝试的: import numpy as np from PIL import ImageGrab, Image img = ImageGrab.grab(bbox=(798, 166, 300, 400)) # (bbox=x,y,width,height) img_np = np.array(img) 但当我尝试打印img\u np时,它返回: <PIL.Image.Image im
numpy
数组的形式对其进行后期处理。这就是我迄今为止所尝试的:
import numpy as np
from PIL import ImageGrab, Image
img = ImageGrab.grab(bbox=(798, 166, 300, 400)) # (bbox=x,y,width,height)
img_np = np.array(img)
但当我尝试打印img\u np
时,它返回:
<PIL.Image.Image image mode=RGB size=0x234 at 0x109F8F0>
它看起来不像是一个numpy
数组。我还想显示numpy
数组中的黑白图像,以验证我所做的是正确的(并且在将来显示处理过的numpy
数组)。有什么我做错了吗?我想你的
(bbox=798, 166, 300, 400))
x=798显示在屏幕上方
所以你必须在你的屏幕上画出你的(x,y)
看这张照片:
结果是无,因为它无法捕获您的屏幕
当我修改x=100时,它就起作用了
守则:
import numpy as np
from PIL import ImageGrab,Image
img=ImageGrab.grab(bbox=(798,166,300,400)) #798
# img=Image.open("Modric.jpg")
print(type(img))
img_np=np.array(img)
print(type(img_np))
print(img_np.shape)
结果:
<class 'PIL.Image.Image'>
<class 'numpy.ndarray'>
() *******None
<class 'PIL.Image.Image'>
<class 'numpy.ndarray'>
(234, 200, 3)
1536 864
(464, 1236)
结果:
<class 'PIL.Image.Image'>
<class 'numpy.ndarray'>
() *******None
<class 'PIL.Image.Image'>
<class 'numpy.ndarray'>
(234, 200, 3)
1536 864
(464, 1236)
结果:
<class 'PIL.Image.Image'>
<class 'numpy.ndarray'>
() *******None
<class 'PIL.Image.Image'>
<class 'numpy.ndarray'>
(234, 200, 3)
1536 864
(464, 1236)
使用bbox=(x,y,width,height)时,像素计数方法为width-x和height-y。所以你必须让你的宽度>x和高度>y,它就可以工作了
至于转换为灰度图像,可以使用opencv
import cv2
gray=cv2.cvtColor(img_np,cv2.COLOR_RGB2GRAY)[enter link description here][3]
链接
或
PIL转换(“L”)函数
img=ImageGrab.grab(bbox=(300,400,width,height)).convert("L") #798
or
公式如下:
def rgb2gray(rgb):
"""
gray=0.299*R+0.587*G+0.144*B
"""
return np.uint8(np.dot(rgb[...,:3], [0.299, 0.587, 0.114]))
正如@Ma Jun指出的 (bbox=x,y,width,height)并不像从(x,y)开始并获得一个从宽到高的窗口。 相反,打开的窗口是x,y宽度-x,高度-y 我添加这篇帖子是因为我花了很长时间才弄明白:)
关键词:Python ImageGrab bbox什么是类型(img)和img\u np.dtype?img的类型是
和img\u np.dtype
返回对象。