Saturday, September 1, 2018

Using Multiple Cameras with OpenCV

As you know, OpenCV is capable of reading from any connected camera in your system, whether it's a built-in webcam (in a laptop) or a USB connected one.

But what if, you wanted to read from more than one cam at the same time?

Can OpenCV handle it?

OpenCV accessing 2 cameras at once
OpenCV accessing 2 cameras at once


Yes, it can!

It's quite simple. Here's how to do it.



You just need to create 2 video capture objects, but read from them in the same main loop.
VideoCapture(0) will be your 'default' camera.
any other cameras connected to the system will be denoted by VideoCapture(1), VideoCapture(2).... and so on.

When displaying the captured frames, make sure you give different names to the 2 OpenCV windows. e.g. cv2.imshow('Cam 0', frame0), cv2.imshow('Cam 1', frame1)
If you give them the same name, OpenCV will attempt to display the two frames in the same window, and you would only see one frame.


Here's the full code to get it working.


import numpy as np
import cv2

video_capture_0 = cv2.VideoCapture(0)
video_capture_1 = cv2.VideoCapture(1)

while True:
    # Capture frame-by-frame
    ret0, frame0 = video_capture_0.read()
    ret1, frame1 = video_capture_1.read()

    if (ret0):
        # Display the resulting frame
        cv2.imshow('Cam 0', frame0)

    if (ret1):
        # Display the resulting frame
        cv2.imshow('Cam 1', frame1)

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

# When everything is done, release the capture
video_capture_0.release()
video_capture_1.release()
cv2.destroyAllWindows()

Make sure you release the video capture objects at the end of the script.

See it in action,


This technique will work for any number of cameras, as long as your machine can handle the load.



Build Deeper: The Path to Deep Learning

Learn the bleeding edge of AI in the most practical way: By getting hands-on with Python, TensorFlow, Keras, and OpenCV. Go a little deeper...

Get your copy now!

3 comments:

  1. Thanks for the code helped me out. Is there a possible way to assign like this:-

    camera 1- videocapture[1]
    camera 2- videocapture[0]
    webcam- videocapture[2]

    ReplyDelete
  2. Well done!! But how can you record and choose to read video/pictures?

    ReplyDelete