如何让 python 检测屏幕上的变化?

问题描述 投票:0回答:1

我想知道如何让 python 检测屏幕部分的变化,并在发生变化时执行某些操作。我不需要它来检测特定的变化,我只需要它来检测任何像素的变化。

我找了很多地方,但找不到任何满足我需求的东西。

python
1个回答
0
投票

要让 Python 检测屏幕特定部分的变化并在发生变化时执行某些操作,您可以使用

Pillow
mss
等第三方库来捕获屏幕并检查是否有任何像素变化。下面的示例展示了如何检测屏幕特定区域中像素的变化。

您可以定期对屏幕的特定部分进行屏幕截图,并将其与之前的屏幕截图进行比较以检测变化。

所需的库

您需要安装以下库:

  1. Pillow
    (用于图像处理)
  2. mss
    (用于截图)

您可以使用以下命令安装它们:

pip install pillow mss

示例代码

import mss
import numpy as np
from PIL import Image
import time

# Set the area of the screen to capture (e.g., a 100x100 area at the top-left corner)
monitor = {"top": 0, "left": 0, "width": 100, "height": 100}

# Use mss to take screenshots
with mss.mss() as sct:
    # Capture the initial screenshot
    previous_screenshot = np.array(sct.grab(monitor))

    while True:
        # Capture the current screenshot
        current_screenshot = np.array(sct.grab(monitor))

        # Compare the current screenshot with the previous one
        if not np.array_equal(current_screenshot, previous_screenshot):
            print("Change detected in the screen area!")
            # Here you can add other actions, like triggering an event
            # Update the previous_screenshot to the current one
            previous_screenshot = current_screenshot
        
        # Wait for 1 second before checking again
        time.sleep(1)

说明:

  1. 使用
    mss
    捕获屏幕的特定区域(例如,100x100 的区域)。
  2. 使用
    numpy
    比较屏幕截图并检查像素变化。
  3. 如果有变化,请执行所需的操作。

您可以根据需要调整屏幕区域大小和时间间隔。

© www.soinside.com 2019 - 2024. All rights reserved.