![](/img/trans.png)
[英]OpenCV cv2.VideoCapture(0) is not working well with webcam
[英]cv2.VideoCapture not working in Jupyter Notebook
我目前正在尝试进行一些视频分类,并且正在使用 anaconda 和 jupyter notebook 来进行数据训练。 但是,我在 jupyter notebook 中遇到了一个错误,我无法使用 cv2.VideoCapture 在我的视频帧中读取,但不知何故它确实在我的 conda 环境的终端中工作。
我确实在某处读到这可能是由于 conda 和 ffmepg 的问题,但我尝试了许多其他人建议的解决方案来解决该问题,包括从 opencv.org 本身下载 opencv 并设置环境路径变量而不是使用 conda install 但它仍然不起作用。
有没有人知道如何解决这个问题?
如果我错了,请原谅我,但我注意到您在两个测试中没有使用相同的文件名。 我被困在同一点,直到我意识到我的“终端测试”和 jupyter notebook 测试之间的路径和文件名不同。 我确认 jupyter 可以访问该文件。
Windows 属性测试:
!attrib data/TownCentreXVID.avi
Bash 文件测试。 有关详细信息,请参阅在 jupyter notebook 中使用 bash 命令:
!file data/TownCentreXVID.avi
然后再试一次,从 jupyter 获得相同的结果没有问题。
Python 中的 OpenCV 使您能够从网络摄像头/或视频文件(如您的情况)中抓取帧作为 Numpy 数组,修改它,然后使用 OpenCV 的 cv2.imshow() 显示它。 为此,OpenCV 将创建一个窗口并将框架推送到那里。 但是,这在 IPython 笔记本中不起作用。
要在 jupyter notebook 或任何其他 IPython notebook 中显示,您必须使用该函数
IPython.display.Image(data)
而不是 OpenCV 的 imshow()。
这是您可以使用的一段代码:
cam = cv2.VideoCapture(0)
d = IPython.display.display("", display_id=1)
d2 = IPython.display.display("", display_id=2)
while True:
try:
t1 = time.time()
frame = get_frame(cam)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
im = array_to_image(frame)
d.update(im)
t2 = time.time()
s = f"""{int(1/(t2-t1))} FPS"""
d2.update( IPython.display.HTML(s) )
except KeyboardInterrupt:
print()
cam.release()
IPython.display.clear_output()
print ("Stream stopped")
break
def get_frame(cam):
# Capture frame-by-frame
ret, frame = cam.read()
#flip image for natural viewing
frame = cv2.flip(frame, 1)
return frame
#Use 'jpeg' instead of 'png' (~5 times faster)
def array_to_image(a, fmt='jpeg'):
#Create binary stream object
f = BytesIO()
#Convert array to binary stream object
PIL.Image.fromarray(a).save(f, fmt)
return IPython.display.Image(data=f.getvalue())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.