如何用Python检测屏幕局部像素变化并触发对应操作?
实现屏幕局部区域像素变化检测的Python方案
核心思路
定时截取指定区域的屏幕画面,对比前后两帧的像素差异,一旦检测到差异就触发指定操作,无需识别具体变化类型。
所需依赖
先安装必要的库:
pip install pyautogui pillow
完整代码实现
import pyautogui from PIL import Image import time def detect_pixel_change(region, check_interval=0.5): # 截取初始基准帧 prev_screenshot = pyautogui.screenshot(region=region) prev_pixels = prev_screenshot.load() width, height = prev_screenshot.size while True: # 截取当前帧 curr_screenshot = pyautogui.screenshot(region=region) curr_pixels = curr_screenshot.load() # 遍历像素对比 has_change = False for x in range(width): for y in range(height): if curr_pixels[x, y] != prev_pixels[x, y]: has_change = True break if has_change: break if has_change: # 替换为你需要执行的操作 print("检测到像素变化!执行指定操作...") # 示例操作:播放提示音 # import winsound # winsound.Beep(1000, 500) # 更新基准帧为当前帧,继续监测 prev_screenshot = curr_screenshot prev_pixels = prev_screenshot.load() time.sleep(check_interval) if __name__ == "__main__": # 监测区域:(左上角x坐标, 左上角y坐标, 区域宽度, 区域高度) # 可运行`pyautogui.displayMousePosition()`获取实时鼠标坐标来确定区域 monitor_region = (100, 100, 300, 200) detect_pixel_change(monitor_region, check_interval=0.5)
关键说明
- 区域定位:执行
pyautogui.displayMousePosition()会实时显示鼠标所在坐标,方便你精准确定监测区域的范围。 - 性能优化:如果监测区域较大,逐像素遍历效率较低,可以改成隔行隔列抽样对比,比如
range(0, width, 2)和range(0, height, 2),减少计算量。 - 自定义操作:在
has_change为True的代码块中,替换成你实际需要触发的逻辑,比如发送通知、启动程序等。 - 停止机制:当前代码为无限循环监测,可添加快捷键监听(比如
pynput库)或其他条件来终止程序。
高效简化版(大区域适用)
如果监测区域较大,可使用像素哈希对比法,计算量更小:
import pyautogui import imagehash import time def detect_change_hash(region, check_interval=0.5): prev_hash = imagehash.average_hash(pyautogui.screenshot(region=region)) while True: curr_hash = imagehash.average_hash(pyautogui.screenshot(region=region)) if curr_hash != prev_hash: print("检测到区域变化!") prev_hash = curr_hash time.sleep(check_interval) # 使用方式与上面一致 detect_change_hash((100, 100, 300, 200))
使用前需额外安装依赖:
pip install imagehash
内容的提问来源于stack exchange,提问作者nathan sitter
相关产品推荐
相关产品推荐

