ImageGrab未捕获精确的bbox图像

2024-09-30 05:22:08 发布

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

我尝试使用pygetwindowImageGrab来获取窗口的位置并对其进行快照,但我得到了某种正确的图像,但也从侧面获得了一些额外的像素。从大小中减去一些像素也没有帮助。我做错了什么,或者有更好更简单的方法吗?还尝试使用win32gui,但得到与图像相同的输出

代码:

import pygetwindow as gw
from time import sleep
from PIL import ImageGrab

win = gw.getWindowsWithTitle('Health Card')[0]
winleft = win.left
wintop = win.top
winright = win.right
winbottom = win.bottom
sleep(3)
print(win.left,win.right,win.bottom,win.top)
a = ImageGrab.grab(bbox=(winleft,wintop,winright,winbottom))
a.save('hey.png')

图片:

enter image description here

我如何才能准确地获取窗口并排除窗口的标题栏

提前感谢:D


Tags: from图像importrighttopsleep像素left
1条回答
网友
1楼 · 发布于 2024-09-30 05:22:08

问题是由于windows 10中的GUI应用了windows阴影

下面是我如何为pygetwindow修复它的:

import pygetwindow as gw
from PIL import ImageGrab
from time import sleep

win = gw.getWindowsWithTitle('Health Card')[0]
winleft = win.left+9
wintop = win.top+38
winright = win.right-9
winbottom = win.bottom-9

sleep(3)
a = ImageGrab.grab(bbox=(winleft,wintop,winright,winbottom))
a.save('trial.png')

或者,如果您正在使用win32gui,请尝试

from win32gui import FindWindow, GetWindowRect
from time import sleep
from PIL import ImageGrab

win = FindWindow(None, 'Health Card')
rect = GetWindowRect(win)
list_rect = list(rect)
list_frame = [-9, -38, 9, 9]
final_rect = tuple(map(lambda x,y:x-y,list_rect,list_frame)) #subtracting two lists

sleep(3)
a = ImageGrab.grab(bbox=final_rect)
a.save('trial.png')

我用map()减去两个列表,你可以用任何你喜欢的方法(例如:numpy

最终输出:

enter image description here

说明: 通常,边框仅用于左、右和底部。我也删除了标题栏,并且我使用了轴差的+cuz。这几乎等同于种植。我认为窗口阴影的标准尺寸是7px,所以我们必须去掉像7-10px这样的东西才能保证准确度

相关问题 更多 >

    热门问题