将图像从屏幕抓取到numpy数组,并将其显示为黑白图像 [英] Grab image from screen to numpy array and display it as black and white image
问题描述
我正在尝试从屏幕的特定位置读取图像数据,因此可以以numpy
数组的形式对其进行后处理.这是我到目前为止尝试过的:
I am trying to read image data from a certain part of the screen, so I can post-process it in a form of a numpy
array. This is what I tried so far:
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_np
时,它返回:
But when I try to print img_np
, it returns:
<PIL.Image.Image image mode=RGB size=0x234 at 0x109F8F0>
它似乎不是一个numpy
数组.我还想显示numpy
数组中的黑白图像,以验证我的操作正确(并且将来还会显示已处理的numpy
数组).我在做错什么吗?
It doesn't seem like it's an numpy
array. I also want to display the black and white image from the numpy
array to verify what I am doing is right (and also display processed numpy
arrays in the future). Is there anything I am doing wrong?
推荐答案
我认为您的
(bbox=798, 166, 300, 400))
x = 798 在您的屏幕上
所以您必须在屏幕上输入(x,y).
so you must make your (x,y) in your screen.
看这张照片: 在此处输入图片描述 结果为无",因为它无法捕获您的屏幕
look this picture: enter image description here the result is None ,because it cant capture your screen
当我修改x = 100时,它可以工作 在此处输入图片描述
and when I modify the x=100,it works enter image description here
代码:
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
在 x = 100 之后:
import numpy as np
from PIL import ImageGrab,Image
img=ImageGrab.grab(bbox=(100,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) code here
结果:
<class 'PIL.Image.Image'>
<class 'numpy.ndarray'>
(234, 200, 3)
右侧的x坐标并在屏幕上可以正常显示
the right x coord and in screen, it can works
对于第一个问题,我很抱歉,右边是这里
I am sorry for the first question,the right is here
import tkinter
win=tkinter.Tk()
width=win.winfo_screenwidth() #get your screen's width
height=win.winfo_screenheight() #get your screen's height
print(width,height)
img=ImageGrab.grab(bbox=(300,400,width,height)).convert("L") #798
img_np=np.array(img)
print(img_np.shape)
结果:
1536 864
(464, 1236)
当您使用bbox = {x,y,width,height)时,像素计数方法是width-x和height-y.因此必须将width> x和height> y设置为可用
when you use the bbox=(x,y,width,height) ,the pixel counting method is width-x and height-y . so you must make your width>x and height>y and it works
要转换为灰度图像,可以使用opencv
as for convert to gray image,you can use opencv
import cv2
gray=cv2.cvtColor(img_np,cv2.COLOR_RGB2GRAY)[enter link description here][3]
链接 或者 PIL convert("L")函数
link or the PIL convert("L") function
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]))
这篇关于将图像从屏幕抓取到numpy数组,并将其显示为黑白图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!