【问题标题】:Grab image from screen to numpy array and display it as black and white image从屏幕抓取图像到 numpy 数组并将其显示为黑白图像
【发布时间】:2023-03-24 11:20:02
【问题描述】:

我正在尝试从屏幕的某个部分读取图像数据,因此我可以以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_np 时,它会返回:

<PIL.Image.Image image mode=RGB size=0x234 at 0x109F8F0>

它似乎不是numpy 数组。我还想显示来自numpy 数组的黑白图像,以验证我所做的是否正确(并且将来还显示处理过的numpy 数组)。是不是我做错了什么?

【问题讨论】:

  • 什么是type(img)和img_np.dtype?
  • img 的类型是 &lt;class 'PIL.Image.Image'&gt;img_np.dtype 返回 object

标签: python-3.x numpy python-imaging-library


【解决方案1】:

我认为你的

(bbox=798, 166, 300, 400))

x=798 出现在您的屏幕上

所以你必须在你的屏幕上显示你的 (x,y)。

看这张图: enter image description here 结果是 None ,因为它无法捕获您的屏幕

当我修改 x=100 时,它可以工作 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坐标和屏幕,它可以工作


对不起第一个问题,正确的在这里

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 。所以你必须让你的宽度>x 和高度>y 并且它可以工作


转灰度图可以用opencv

import cv2
gray=cv2.cvtColor(img_np,cv2.COLOR_RGB2GRAY)[enter link description here][3]

链接 或者 PIL convert("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]))

【讨论】:

    【解决方案2】:

    正如@Ma Jun 指出的那样 (bbox=x,y,width,height) 并不像从 (x,y) 开始并获得宽度到高度的窗口。 而是打开窗口是 x,y width-x, height-y 我添加了这篇文章,因为我花了很长时间才弄清楚这一点:) 关键词:Python ImageGrab bbox

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 2014-02-07
      • 2021-01-08
      • 2011-02-09
      相关资源
      最近更新 更多