使用mss完成多屏幕截图
可以通过pip install mss
安装mss工具库。
第1块屏幕
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)
第2块屏幕
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)
配合opencv对第2块屏幕截图
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)
补充点
sct.monitors # 如果只有一块屏幕
[{'left': 0, 'top': 0, 'width': 1366, 'height': 768},
{'left': 0, 'top': 0, 'width': 1366, 'height': 768}]
sct.monitors # 如果有2块屏幕
[{'left': 0, 'top': 0, 'width': 3286, 'height': 1080},
{'left': 1920, 'top': 0, 'width': 1366, 'height': 768},
{'left': 0, 'top': 0, 'width': 1920, 'height': 1080}]