如何使用 OpenCV 从网络摄像头读取视频?
How do I read a video from a webcam with OpenCV?
我正在关注 the official documentation,试图从网络摄像头读取视频。正如我 运行 文档中的一段代码:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
失败,输出如下:
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /io/opencv/modules/imgproc/src/color.cpp, line 9748
Traceback (most recent call last):
File "capture.py", line 11, in
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: /io/opencv/modules/imgproc/src/color.cpp:9748: error: (-215) scn == 3 || scn == 4 in function cvtColor
进一步检查发现:
ret
总是 False
.
- 加上
cap.get(3)
(得到图片的宽度)returns 0.0
.
- 如果我测试
cap.isOpened()
,结果总是 False
。
- 如果我添加对
cap.open(0)
的调用,open
returns False
也一样。
- 调用
cap.open("/dev/video0")
没有任何改变。
- 将
cap = cv2.VideoCapture(0)
替换为 cap = cv2.VideoCapture("/dev/video0")
无效。
在 VLC 中打开 /dev/video0
会显示来自网络摄像头的视频。当我打开 Cheese 时,它还会显示来自网络摄像头的视频。电脑上只有一台相机连接。
有什么建议吗?
您可能缺少 FFMPEG。 OpenCV需要解码器信息来解码ffmpeg提供的视频,打开相机等。
在 Windows 上安装 FFmpeg 的步骤详见此处 http://www.wikihow.com/Install-FFmpeg-on-Windows。遵循 Linux 等价物可能会解决您的问题
我正在关注 the official documentation,试图从网络摄像头读取视频。正如我 运行 文档中的一段代码:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
失败,输出如下:
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /io/opencv/modules/imgproc/src/color.cpp, line 9748
Traceback (most recent call last):
File "capture.py", line 11, in
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: /io/opencv/modules/imgproc/src/color.cpp:9748: error: (-215) scn == 3 || scn == 4 in function cvtColor
进一步检查发现:
ret
总是False
.- 加上
cap.get(3)
(得到图片的宽度)returns0.0
. - 如果我测试
cap.isOpened()
,结果总是False
。 - 如果我添加对
cap.open(0)
的调用,open
returnsFalse
也一样。 - 调用
cap.open("/dev/video0")
没有任何改变。 - 将
cap = cv2.VideoCapture(0)
替换为cap = cv2.VideoCapture("/dev/video0")
无效。
在 VLC 中打开 /dev/video0
会显示来自网络摄像头的视频。当我打开 Cheese 时,它还会显示来自网络摄像头的视频。电脑上只有一台相机连接。
有什么建议吗?
您可能缺少 FFMPEG。 OpenCV需要解码器信息来解码ffmpeg提供的视频,打开相机等。
在 Windows 上安装 FFmpeg 的步骤详见此处 http://www.wikihow.com/Install-FFmpeg-on-Windows。遵循 Linux 等价物可能会解决您的问题