使用cv2.VideoCapture捕获图片

时间:2019-05-18 07:50:05

标签: python opencv

我想使用我的笔记本电脑网络摄像头通过以下代码捕获图片:

import cv2
cap = cv2.VideoCapture(1)
while(True):
    ret, frame = cap.read()
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()


cv2.destroyAllWindows()

但是会引发此错误:

  

cv2.imshow('frame',frame)cv2.error:OpenCV(4.0.0)   C:\ projects \ opencv-python \ opencv \ modules \ highgui \ src \ window.cpp:350:   错误:(-215:声明失败)size.width> 0 && size.height> 0 in   函数'cv :: imshow'

如何解决此错误?

2 个答案:

答案 0 :(得分:1)

if user is not None: # authenticate the user auth.login(request, user) # Fetch additional information about the user # fetching presonal-Information try: personal_info = PersonalInformation.objects.get(user_id=user.id) except ObjectDoesNotExist: personal_info = None return redirect('dashboard', personal_info) else: messages.error(request, 'Invalid credentials') return redirect('login') else: return render(request, 'pages/login.html') 无法从摄像机或流中获取帧时,它不会引发错误,但会在OpenCV中返回False(返回状态),因此您应进行检查。它还会在ret中返回None,并且frame不能显示imshow-它没有宽度和高度-因此您会遇到None

据我所知,笔记本电脑的网络摄像头大多是数字size.width>0 && size.height>0,而不是0

该功能可用于我的笔记本电脑网络摄像头

1

编辑:,如Dave W. Smith在评论中所说:一些笔记本电脑可能需要一些时间来发送正确的图像,然后此处的版本不会退出循环

import cv2

cap = cv2.VideoCapture(0) # zero instead of one

while True:
    ret, frame = cap.read()

    if not ret: # exit loop if there was problem to get frame to display
        break

    cv2.imshow('frame', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

答案 1 :(得分:-1)

import numpy as np
import cv2

cap = cv2.VideoCapture(0)  #it can be one also...but generally zero

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    cv2.imshow('Capture', frame)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

尝试这个...适用于我的...确保已安装numpy