欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python实用模块(三十七)python-mss

实用模块 迷途小书童 2年前 (2022-09-22) 3175次浏览 0个评论

环境

  • windows 10 64bit
  • python 3.8
  • mss 6.1.0

前言

python-mss 是一个速度非常快的截图工具,支持跨平台,使用纯 python 语言开发。

安装

使用 pip 安装,执行命令

pip install mss

python-mss 还提供了命令行工具,使用 mss 就可以直接截取屏幕,默认是全屏

python-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')

第二个实例,我们来看看如何录屏?这里,需要借助一下 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/

喜欢 (0)

您必须 登录 才能发表评论!