Skip to content Skip to sidebar Skip to footer

Use Cv2.videocapture To Capture A Picture

I want to use my laptop webcam to capture a picture using the code below: import cv2 cap = cv2.VideoCapture(1) while(True): ret, frame = cap.read() cv2.imshow('frame', fram

Solution 1:

When OpenCV has problem to get frame from camera or stream then it doesn't raise error but it return False in ret (return status) so you should check it. It also return None in frame and imshow has problem to display None - it has no width and height - so you get error with size.width>0 && size.height>0

As I know mostly laptop webcame has number 0, not 1

This works with my laptop webcam

import cv2

cap = cv2.VideoCapture(0) # zero instead of onewhileTrue:
    ret, frame = cap.read()

    ifnot ret: # exit loop if there was problem to get frame to displaybreak

    cv2.imshow('frame', frame)

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

cap.release()
cv2.destroyAllWindows()

EDIT: as said Dave W. Smith in comment: some laptops may need time to send correct image then here version which doesn't exit loop

whileTrue:
    ret, frame = cap.read()

    if ret: # display only if status (ret) is True and there is frame
        cv2.imshow('frame', frame)

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

Solution 2:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)  #it can be one also...but generally zerowhile(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()

Try this one...it works for mine...make sure numpy is installed

Post a Comment for "Use Cv2.videocapture To Capture A Picture"