Sam*_*dar 4 python linux windows macos python-3.x
我在 python 中使用pyautogui来获取屏幕截图
import pyautogui
screen = pyautogui.screenshot()
screen.save("file.jpg")
Run Code Online (Sandbox Code Playgroud)
它在所有平台上的单个屏幕上运行良好。但在多屏幕系统中,它将两个屏幕组合在一个屏幕截图中。但我想要一张当前正在使用的显示器的屏幕截图。
小智 8
mss包可以轻松解决这个问题pip install mss
第一监视器
import os
import os.path
import mss
def on_exists(fname):
# type: (str) -> None
"""
Callback example when we try to overwrite an existing screenshot.
"""
if os.path.isfile(fname):
newfile = fname + ".old"
print("{} -> {}".format(fname, newfile))
os.rename(fname, newfile)
with mss.mss() as sct:
filename = sct.shot(output="mon-{mon}.png", callback=on_exists)
print(filename)
Run Code Online (Sandbox Code Playgroud)
第二监视器
import mss
import mss.tools
with mss.mss() as sct:
# Get information of monitor 2
monitor_number = 2
mon = sct.monitors[monitor_number]
# The screen part to capture
monitor = {
"top": mon["top"],
"left": mon["left"],
"width": mon["width"],
"height": mon["height"],
"mon": monitor_number,
}
output = "sct-mon{mon}_{top}x{left}_{width}x{height}.png".format(**monitor)
# Grab the data
sct_img = sct.grab(monitor)
# Save to the picture file
mss.tools.to_png(sct_img.rgb, sct_img.size, output=output)
print(output)
Run Code Online (Sandbox Code Playgroud)
与 OpenCV 一起使用
import mss
import cv2
import numpy as np
with mss.mss() as sct:
# Get information of monitor 2
monitor_number = 2
mon = sct.monitors[monitor_number]
# The screen part to capture
monitor = {
"top": mon["top"],
"left": mon["left"],
"width": mon["width"],
"height": mon["height"],
"mon": monitor_number,
}
output = "sct-mon{mon}_{top}x{left}_{width}x{height}.png".format(**monitor)
# Grab the data
sct_img = sct.grab(monitor)
img = np.array(sct.grab(monitor)) # BGR Image
# Display the picture
cv2.imshow("OpenCV", img)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)
sct.monitors即使您只有一个显示器,也会包含多个项目,因为第一个项目将是组合屏幕>>> sct.monitors # if we have a single monitor
[{'left': 0, 'top': 0, 'width': 1366, 'height': 768},
{'left': 0, 'top': 0, 'width': 1366, 'height': 768}]
Run Code Online (Sandbox Code Playgroud)
>>> sct.monitors # if we have two monitors
[{'left': 0, 'top': 0, 'width': 3286, 'height': 1080},
{'left': 1920, 'top': 0, 'width': 1366, 'height': 768},
{'left': 0, 'top': 0, 'width': 1920, 'height': 1080}]
Run Code Online (Sandbox Code Playgroud)
小智 5
在这里找到了解决方案!
from PIL import ImageGrab
from functools import partial
ImageGrab.grab = partial(ImageGrab.grab, all_screens=True)
Run Code Online (Sandbox Code Playgroud)
pyautogui.screenshot() 将捕获所有屏幕。