Home > Software design >  opencv cap = cv2.VideoCapture(0) takes a long time to open the webcam please give me a solution
opencv cap = cv2.VideoCapture(0) takes a long time to open the webcam please give me a solution

Time:11-24

opencv cap = cv2.VideoCapture(0) takes a long time to open the webcam please give me a solution

I tried cap = cv2.VideoCapture(1) doesnt work takes a long time too

CodePudding user response:

If you got any kind of warnings, you may need to search for how to fix those warnings.

Or you can try to specify the video source. For example:

# If you are using Windows
cap = cv2.VideoCapture(1, cv2.CAP_DSHOW)

# If you are using Linux
cap = cv2.VideoCapture(1, cv2.CAP_V4L2)

CodePudding user response:

The DSHOW backend API is faster.

On windows:

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

CodePudding user response:

This takes 0.9692582 seconds vs 5.8355613;

import cv2
import os

cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)

e1 = cv2.getTickCount()

print(os.name)
# detect operating system 
if os.name != 'nt':
    # Not Windows
    cap = cv2.VideoCapture(1, cv2.CAP_V4L2)

ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(
    thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(frame, contours, -1, (0, 255, 0), 3)
e2 = cv2.getTickCount()
time = (e2 - e1) / cv2.getTickFrequency()
print(time)

cv2.imshow('frame', frame)
cv2.waitKey(0)
cap.release()
cv2.destroyAllWindows()

Output:

ME

  • Related