如何在Python中捕获非活动窗口的特定区域?
我已经成功满足了两个第一个条件,但是我在最后一个条件上遇到了困难,这是我的代码
import win32gui, win32ui
from ctypes import windll
from PIL import Image
def capture_screen():
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
rect = win32gui.GetWindowRect(hwnd)
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, rect[2], rect[3]) # figure a way to capture only a part of the screen instead
saveDC.SelectObject(saveBitMap)
result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 2)
bmpinfo = saveBitMap.GetInfo()
bmpstr = saveBitMap.GetBitmapBits(True)
image = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1)
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)
return image
WINDOW_NAME = 'Play Chrome Dinosaur Game Online - elgooG - Google Chrome'
hwnd = win32gui.FindWindow(None, WINDOW_NAME)
screen_capture = capture_screen()
screen_capture.save('window_capture.png')
这是正在保存的图片: 全屏恐龙
这是我的目标: 所需输出
我已经通过从位图缓冲区创建 NumPy 数组、重塑数组以表示图像尺寸,然后选择所需的高度范围来解决我的问题
import win32gui, win32ui
import numpy as np
from ctypes import windll
from PIL import Image
def capture_screen():
w, h = win32gui.GetWindowRect(hwnd)[2:]
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
saveDC.SelectObject(saveBitMap)
result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 2)
bmpstr = saveBitMap.GetBitmapBits(True)
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)
img = np.frombuffer(bmpstr, dtype='uint8')
img.shape = (h, w, 4)
capture_game_screen = img[370:800]
pil_img = Image.fromarray(capture_game_screen)
return pil_img
WINDOW_NAME = 'Play Chrome Dinosaur Game Online - elgooG - Google Chrome'
hwnd = win32gui.FindWindow(None, WINDOW_NAME)
screen_capture = capture_screen()
screen_capture.show()
很想看看是否有人有更好的内存效率分辨率