import cv2 cap = cv2.VideoCapture(0) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = cap.get(cv2.CAP_PROP_FPS) fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V') out = None if not cap: print("打开摄像头失败") while True: success, frame = cap.read() if success: cv2.imshow("frame", frame) out = cv2.VideoWriter('./video/save.mp4', fourcc, fps, (width, height)) out.write(frame) key = cv2.waitKey(0) if key == ord('q'): break cv2.destroyAllWindows() out.release()这段代码有错吗 为什么只能显示一帧视频
时间: 2024-04-16 20:26:13 浏览: 165
OpenCV2从摄像头获取帧并写入视频文件的方法
根据你提供的代码,有几个问题可能导致能显示一帧视频:
1. `out = cv2.VideoWriter('./video/save.mp4', fourcc, fps, (, height))` 这一行代码应该放在循环外部,否则每一帧都会创建一个新的`VideoWriter`对象,这可能导致只保存最后一帧。
2. `out.write(frame)` 这一行代码应该在`if success`条件的内部,以确保只有在成功读取到帧时才进行写入操作。
3. `key = cv2.waitKey(0)` 这一行代码应该放在帧显示之后,以确保能够正常响应键盘输入。
下面是修改后的代码:
```python
import cv2
cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V')
out = cv2.VideoWriter('./video/save.mp4', fourcc, fps, (width, height))
if not cap:
print("打开摄像头失败")
while True:
success, frame = cap.read()
if success:
cv2.imshow("frame", frame)
out.write(frame)
key = cv2.waitKey(1)
if key == ord('q'):
break
cv2.destroyAllWindows()
out.release()
```
修改后的代码应该能够正常显示并保存视频。如果还有其他问题,请随时提问。
阅读全文