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

如何实现每5分钟一次的摄像头图像采集与图像处理循环

每5分钟自动执行的摄像头图像采集与处理流程

我需要用Python实现从摄像头捕获图像,依次完成高斯模糊、灰度转换、阈值处理及特征点标记操作,并且整套流程每5分钟自动重复执行。以下是修正后的可运行代码:

import time
import cv2
import numpy as np

def process_camera_frame():
    # 1. 摄像头图像采集
    videoCaptureObject = cv2.VideoCapture(0)
    # 只捕获一帧图像
    ret, frame = videoCaptureObject.read()
    if not ret:
        print("无法从摄像头捕获图像")
        videoCaptureObject.release()
        return
    
    cv2.imwrite("NewPicture.jpg", frame)
    videoCaptureObject.release()
    
    # 2. 图像处理流程
    image = cv2.imread('NewPicture.jpg')
    if image is None:
        print("无法读取保存的图像")
        return
    
    # 高斯模糊
    blur = cv2.GaussianBlur(image, (3,3), 0)
    # 灰度转换
    gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)
    # 阈值处理
    thresh = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY_INV)[1]
    
    # 计算特征点坐标
    x, y, w, h = cv2.boundingRect(thresh)
    if w == 0 or h == 0:
        print("未检测到有效特征区域")
        return
    
    left = (x, np.argmax(thresh[:, x]))
    right = (x+w-1, np.argmax(thresh[:, x+w-1]))
    top = (np.argmax(thresh[y, :]), y)
    bottom = (np.argmax(thresh[y+h-1, :]), y+h-1)
    
    # 绘制特征点
    cv2.circle(image, left, 8, (0, 50, 255), -1)
    cv2.circle(image, right, 8, (0, 255, 255), -1)
    cv2.circle(image, top, 8, (255, 50, 0), -1)
    cv2.circle(image, bottom, 8, (255, 255, 0), -1)
    
    # 输出特征点坐标
    print('left: {}'.format(left))
    print('right: {}'.format(right))
    print('top: {}'.format(top))
    print('bottom: {}'.format(bottom))
    
    # 显示结果(自动执行场景可注释)
    # cv2.imshow('thresh', thresh)
    # cv2.imshow('image', image)
    # cv2.waitKey(1000)  # 显示1秒后自动关闭窗口
    # cv2.destroyAllWindows()

# 循环执行,每5分钟一次
if __name__ == "__main__":
    while True:
        process_camera_frame()
        print("等待5分钟后执行下一次...")
        time.sleep(300)  # 300秒 = 5分钟

关键修正说明

  • 将采集与处理逻辑封装为函数,结构更清晰易维护
  • 移除原代码中的死循环,改为单次捕获一帧图像
  • 增加图像读取、捕获的异常判断,避免程序崩溃
  • 调整cv2.waitKey()为带超时版本(或直接注释),避免阻塞自动执行流程
  • 在外层添加无限循环,通过time.sleep(300)实现每5分钟执行一次
  • 统一导入语句位置,符合Python编码规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:40:26