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

使用OpenCV结合schedule定时捕获摄像头图像时视图器卡顿重复生成同一张图的问题求助

Hey there, let's figure out why your scheduled webcam captures are saving the same image every time!

The Root Cause

Your code splits the webcam frame updating and scheduled task execution into two separate, disconnected loops:

  • The first while True loop reads and displays live webcam frames, but it only exits when you press the ESC key.
  • Once you exit that loop, you enter the schedule-specific loop—but by then, the frame variable stops updating entirely. It’s stuck on the last frame from before you pressed ESC, so every capture() call saves that same static image.

The Fix

We need to merge the schedule task check into the main webcam loop, so we’re always working with the latest frame when the scheduled capture runs. Here’s the revised code:

import cv2
import time
import schedule

cam = cv2.VideoCapture(0)
cv2.namedWindow("Webcam")
img_counter = 0

def capture(current_frame):
    global img_counter
    img_name = "opencv_frame_{}.png".format(img_counter)
    cv2.imwrite(img_name, current_frame)
    print(f"Saved screenshot: {img_name}")
    img_counter += 1

# Set up the scheduled task initially (we'll update the frame argument later)
schedule.every(5).seconds.do(capture, current_frame=None)

while True:
    ret, frame = cam.read()
    if not ret:
        print("Failed to grab frame")
        break
    
    # Update the scheduled task's argument to the latest live frame
    for job in schedule.get_jobs():
        job.args = [frame]
    
    # Show the live webcam feed
    cv2.imshow("Webcam", frame)
    
    # Check if it's time to run the capture task
    schedule.run_pending()
    
    # Handle exit via ESC key
    k = cv2.waitKey(1)
    if k % 256 == 27:
        print("Closing the app")
        break

# Clean up resources properly
cam.release()
cv2.destroyAllWindows()

Key Changes Explained

  1. Merged Loops: We moved schedule.run_pending() into the main webcam loop, so we check for pending capture tasks every time we read a new frame.
  2. Pass Latest Frame to Capture: Instead of relying on a static global frame variable, we update the scheduled task’s arguments with the newest frame each loop. This ensures capture() always saves the current live image.
  3. Removed Redundant Loop: The separate while 1 schedule loop is no longer needed—everything runs in the single main loop that handles webcam input and user interaction.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 09:03:14