使用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 Trueloop 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
framevariable stops updating entirely. It’s stuck on the last frame from before you pressed ESC, so everycapture()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
- 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. - Pass Latest Frame to Capture: Instead of relying on a static global
framevariable, we update the scheduled task’s arguments with the newest frame each loop. This ensurescapture()always saves the current live image. - Removed Redundant Loop: The separate
while 1schedule loop is no longer needed—everything runs in the single main loop that handles webcam input and user interaction.
内容的提问来源于stack exchange,提问作者Shajahan A
相关产品推荐
相关产品推荐

