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.

1 comment:

  1. Your content is nothing short of bright in many forms. I think this is friendly and eye-opening material. I have gotten so many ideas from your blog. Thank you so much. Best Smoke Detector Cameras

    ReplyDelete