1
votes

I want to capture an image from 2 webcams connected to my computer using opencv and python. This is the code which i have written:

    #to take snapshot from two webcams simultaneously
    import cv2
    import cv2.cv as cv
    import numpy as np 
    left = cv2.VideoCapture(1)  #capturing video from device port 1 aka webcam1
    right = cv2.VideoCapture(2) #capturing video from device port 2 aka webcam2
    capture_left=cv.CaptureFromCAM(1)   
    capture_right =cv.CaptureFromCAM(2)
    while(True):
       ret,frameL = left.read()
       ret1,frameR = right.read()
       rgb_left = cv2.cvtColor(frameL,0)
       rgb_right = cv2.cvtColor(frameR,0)
       cv2.imshow('frameL',rgb_left)
       cv2.imshow('frameR',rgb_right)
       k=cv2.waitKey(0)
       if k == 27:         # wait for ESC key to break
           break
        elif k == 32: # wait for spacebar to click snapshot
           il=cv.QueryFrame(capture_left)
           cv.SaveImage("defaultL.jpg",il)
           ir=cv.QueryFrame(capture_right)
           cv.SaveImage("defaultR.jpg",ir)

    left.release()
    right.release()
    cv2.destroyAllWindows()

But on execution this was the error: OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor, file ........\opencv\modules\imgproc\src\color.cpp, line 3648 Traceback (most recent call last): File "C:\Users\Administrator\Desktop\capturing.py", line 15, in rgb_right = cv2.cvtColor(frameR,0) cv2.error: ........\opencv\modules\imgproc\src\color.cpp:3648: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor

[Finished in 1.5s with exit code 1]

1
please avoid the old cv api. mixing both is a receipe for desaster - berak
if your cameras need some 'warmup' time, you migt have to ignore the 1st (invalid/empty) frame. check the ret value from read(), and just continue - berak

1 Answers

0
votes

Add the following line to check the data. If have data, process, if not, continue

if np.shape(frameL) == ():
       do nothing and let it pass
else
       do the shit you want

if np.shape(frameR) == ():
       do nothing and let it pass
else
       do the shit you want

also, add checking for channels

if(len(frameL.shape)>2)
     rgb_left = cv2.cvtColor(frameL,0)
else
     rgb_left = frameL

that should solve all Assertion failed issue

PS. this method probably won't give you data simultaneously. So dont expect perfect stereo depth output.

If you want real simultaneously, you need hardware sync, the trigger for your camera. Then multi-thread event handle for camera stream. Then bind data for processing.

I did a similar thing using C++. python not so sure about the whole process.

This is Speaking from experience.