使用OpenCV保存视频文件时出现错误,请求排查代码问题
Hey there, let's break down why your code is failing and get it working properly. The error points to line 5 (the FourCC setup), but there are a few other potential pitfalls in the code we should address too:
Key Issues & Fixes
1. Invalid FourCC Code
The 'VID' code you're using isn't a valid codec recognized by OpenCV. Different operating systems support different codecs, so use one that's compatible:
- For Windows: Use
'XVID'or'DIVX' - For Linux/macOS:
'MJPG'is a reliable cross-platform option
Update the FourCC line to:
fourcc = cv2.VideoWriter_fourcc(*'XVID')
2. Incorrect Camera Index
You're using cv2.VideoCapture(1), but most systems default to the first webcam at index 0. If you only have one camera, this will fail to open the stream entirely. Switch to index 0 first, or test indices to find your active camera:
cap = cv2.VideoCapture(0)
3. Mismatched Frame Dimensions
You've hardcoded the output resolution to (640, 480), but your webcam might capture frames at a different size. If the dimensions don't match, the VideoWriter will fail to save the video. Instead, grab the actual resolution from the camera:
# Get actual camera frame size width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # Initialize VideoWriter with correct dimensions out = cv2.VideoWriter('output.avi', fourcc, 20.0, (width, height))
4. Missing Error Checks
Your code doesn't verify if the camera opened successfully or if frames are being read properly. Add these checks to avoid cryptic errors:
- Check if the camera opened:
if not cap.isOpened(): print("Couldn't open the camera!") exit() - Check if each frame was read correctly in the loop:
ret, frame = cap.read() if not ret: print("Stream ended or failed to read frame. Exiting...") break
Full Corrected Code
import numpy as np import cv2 # Initialize camera (use 0 for default webcam) cap = cv2.VideoCapture(0) # Check if camera opened successfully if not cap.isOpened(): print("Couldn't open the camera!") exit() # Use valid FourCC codec (XVID works on most systems) fourcc = cv2.VideoWriter_fourcc(*'XVID') # Get actual camera frame dimensions width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # Initialize VideoWriter with correct parameters out = cv2.VideoWriter('output.avi', fourcc, 20.0, (width, height)) while(True): ret, frame = cap.read() # Check if frame was read successfully if not ret: print("Stream ended or failed to read frame. Exiting...") break # Convert frame to grayscale for display gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Save the original color frame to video out.write(frame) # Display grayscale frame cv2.imshow('frame', gray) # Exit on 'q' key press if cv2.waitKey(1) & 0xFF == ord('q'): break # Release all resources properly cap.release() out.release() cv2.destroyAllWindows()
This should fix the video saving error and make your code more robust against common webcam issues.
内容的提问来源于stack exchange,提问作者Aniket Bote




