環境
ウィンドウズ10 64ビット
パイソン3.8
ミリ秒 6.1.0
序文
python-mss
クロスプラットフォームをサポートし、純粋なpython
言語。
インストール
コマンドを使用してpip
インストールする
pip install mss
python-mss
コマンドラインツールも提供されており、それを使用しmss
て。デフォルトはフルスクリーンです
その他の使用可能なパラメーターmss -h
は
$ mss -h
usage: mss [-h] [-c COORDINATES] [-l {0,1,2,3,4,5,6,7,8,9}] [-m MONITOR]
[-o OUTPUT] [-q] [-v]
optional arguments:
-h, --help show this help message and exit
-c COORDINATES, --coordinates COORDINATES
the part of the screen to capture: top, left, width,
height
-l {0,1,2,3,4,5,6,7,8,9}, --level {0,1,2,3,4,5,6,7,8,9}
the PNG compression level
-m MONITOR, --monitor MONITOR
the monitor to screen shot
-o OUTPUT, --output OUTPUT
the output file name
-q, --quiet do not print created files
-v, --version show program's version number and exit
実用的
2 つの部分の内容を見てみましょう。最初の部分はスクリーンショットで、基本的な機能でもあります。
# 导入模块
import mss
# 实例化对象
with mss.mss() as sct:
# 通过参数output指定保存的文件名
sct.shot(output='output.png')
shot
メソッドにはパラメーターもありますcallback
。これは、コールバックを使用するのに便利です
import mss
def fun_callback(filename):
# 作为示例,打印下截取的文件名
print(filename)
with mss.mss() as sct:
# 通过参数output指定保存的文件名
filename = sct.shot(output='output.png', callback=fun_callback)
ウィンドウの一部を傍受する場合
import mss
with mss.mss() as sct:
# 设置一个区域,top为距离屏幕左上角的垂直方向上的距离,left是水平方向的距离,后面2个分别是宽和高
monitor = {"top":50, "left":50, "width": 600, "height": 400}
image_sct = sct.grab(monitor)
# 转换成png保存起来
mss.tools.to_png(image_sct.rgb, image_sct.size, output="output.png")
mss
画像形式を に変換する必要がある場合はPIL
、これを行うことができます
import mss
from PIL import Image
with mss.mss() as sct:
# 设置一个区域,top为距离屏幕左上角的垂直方向上的距离,left是水平方向的距离,后面2个分别是宽和高
monitor = {"top":50, "left":50, "width": 600, "height": 400}
image_sct = sct.grab(monitor)
image_pil = Image.frombytes('RGB', image_sct.size, image_sct.bgra, 'raw', 'BGRX')
image_pil.save('output_pil.png')
2 番目の例では、画面を記録する方法を見てみましょう。ここでは、それを使用する必要がありますopencv
。コードを見てください。
import mss
import cv2
import numpy as np
from PIL import Image
monitor = {"top":50, "left":50, "width": 600, "height": 400}
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
fps = 20
video = cv2.VideoWriter('output.avi', fourcc, fps, (600, 400))
with mss.mss() as sct:
# 设置一个区域,top为距离屏幕左上角的垂直方向上的距离,left是水平方向的距离,后面2个分别是宽和高
while True:
image_sct = sct.grab(monitor)
image_pil = Image.frombytes('RGB', image_sct.size, image_sct.bgra, 'raw', 'BGRX')
image_cv = np.array(image_pil)
video.write(image_cv)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
video.release()
詳細については、公式リンク https://github.com/BoboTiG/python-mss を参照してください。
Python実用モジュールに関するトピック
より便利なpython
モジュール、に移動してください
https://xugaoxiang.com/category/python/modules/