Opencv webcam script endlessly turns webcams off and on
<p>I wrote a script to display a depth map from my webcams:</p>

<pre><code>cam_a = int(sys.argv[1])
cam_b = int(sys.argv[2])


while True:
    imgl = cv2.VideoCapture(cam_a).read()[1]
    imgL = cv2.cvtColor(imgl, cv2.COLOR_BGR2GRAY)

    imgr = cv2.VideoCapture(cam_b).read()[1]
    imgR = cv2.cvtColor(imgr, cv2.COLOR_BGR2GRAY)


    stereo = cv2.StereoBM(cv2.STEREO_BM_BASIC_PRESET,ndisparities=16, SADWindowSize=15)
    disparity = stereo.compute(imgL,imgR)

    cv2.imshow('Disparity', disparity)
</code></pre>

<p>And while it doesn't give me an error, it does flash both of my webcams off and on, endlessly. I'm worried this might break my webcams, how can I stop this?</p>

<p><strong>EDIT</strong></p>

<p>So, I changed it so that it only shows one camera as a normal video:</p>

<pre><code>while True:
    imgl = cv2.VideoCapture(cam_a).read()[1]
    imgL = cv2.cvtColor(imgl, cv2.COLOR_BGR2GRAY)

    #imgr = cv2.VideoCapture(cam_b).read()[1]
    #imgR = cv2.cvtColor(imgr, cv2.COLOR_BGR2GRAY)


    #stereo = cv2.StereoBM(cv2.STEREO_BM_BASIC_PRESET,ndisparities=16, SADWindowSize=15)
    #disparity = stereo.compute(imgL,imgR)

    cv2.imshow('Disparity', imgL)
    cv2.waitKey(10)
</code></pre>

<p>And it <em>still</em> just flashes the camera on and off. I'm not sure what to change here.</p>

<p>Got the problem. You are continuously initiating videocapture object under the while loop. You should use one instance initiated before while loop and access image using that instance of videocapture. See this example and change your code accordingly, hope it will fix your issues:</p>

<pre><code>import cv2
camera = cv2.VideoCapture(0)
while True:
    return_value,image = camera.read()
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    cv2.imshow('image',gray)
    if cv2.waitKey(1)&amp; 0xFF == ord('s'):
        cv2.imwrite('test.jpg',image)
        break
camera.release()
cv2.destroyAllWindows()
</code></pre>

python opencv video webcam depth