You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现主屏幕截图转灰度图求平均像素值无输出问题

问题分析与修复方案

两段代码均无输出,核心问题如下:

  • 未导入time模块,无法使用sleep()函数,运行会直接报错
  • 未调用定义好的函数(代码一的screen_record()、代码二的main()),导致逻辑根本没执行
  • 代码一存在变量名错误:使用了未定义的screen变量,应替换为处理好的image

修复后的完整代码(基于代码二优化)

import numpy as np
from PIL import ImageGrab
import cv2
import time  # 必须导入time模块

def process_img(image):
    # 转为灰度图
    processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    return processed_img

def main():
    while True:
        # 截取主屏幕
        screen = np.array(ImageGrab.grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=None))
        # 转为灰度图
        gray_screen = process_img(screen)
        # 计算并打印平均像素值
        mean_pixel = np.mean(gray_screen)
        print(f"灰度图平均像素值:{mean_pixel}")
        # 间隔30秒循环
        time.sleep(30)

# 启动主逻辑
if __name__ == "__main__":
    main()

关键修复点说明

  1. 补充import time,调用time.sleep(30)实现固定间隔
  2. 添加if __name__ == "__main__": main(),确保主函数被执行
  3. 代码一的变量错误修复:将new_screen = process_img(screen)改为new_screen = process_img(image),同时补全time导入和函数调用

运行修复后的代码,PyCharm会每隔30秒输出一次当前屏幕灰度图的平均像素值。

内容的提问来源于stack exchange,提问作者mcphervi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:40:37