Set Up USB Camera for OpenCV Projects with Raspberry Pi

This guide shows how to set up a USB camera for your OpenCV projects with Raspberry Pi. OpenCV can be used with the Raspberry Pi camera and with regular USB cameras (also known as webcams). In all our OpenCV projects, we will be using a USB camera.

Raspberry Pi Set Up USB Camera for OpenCV Projects

Prerequisites

Before proceeding, make sure you check all the following prerequisites:

Raspberry Pi with USB Camera

In our OpenCV projects, we will be using the Raspberry Pi with a regular USB camera, like the one shown in the picture below.

USB Camera Webcam Raspberry Pi compatible

Here are a few advantages and disadvantages of using a USB camera:

  • If you already have a USB camera, you can try to use it with your OpenCV projects and you don’t need to spend any extra money on a Raspberry Pi-specific camera.
  • If your OpenCV application requires high-quality image/video, you can buy a USB camera that can offer more quality or other specific features that are required for your project needs (higher image quality, faster frame rates, and more flexibility in terms of mounting and lens options).
  • However, USB cameras might be a bit more tricky to set up since they can have driver incompatibility issues when used with the Raspberry Pi.
  • For Raspberry Pi projects using OpenCV, we recommend using a webcam from a well-known brand like Logitech to prevent driver incompatibility issues.

In summary, the best choice for you will depend on your project requirements. In this guide, we’ll show you how to set up OpenCV with a USB camera.

Connect your camera to the Raspberry Pi USB port before proceeding.

Raspberry Pi USB Camera webcam connected

List Your USB Devices

On a Terminal window on your Raspberry Pi, run the next command to list all video devices:

v4l2-ctl --list-devices

In our case, we are using an HD Pro Webcam C920 by Logitech and we’ve highlighted it in the screenshot below.

Raspberry Pi list all USB devices to find id of webcam

Even though it lists three video devices, usually the USB camera id is the one at the first line. In our case:

/dev/video0

This means that for our OpenCV projects the camera id is 0, yours might be different.

OpenCV Test USB Camera – Python Script

We’ve created a simple OpenCV Python script to test if your USB camera is compatible with the Raspberry Pi and can be used in future projects.

Start by creating a new file called opencv_test_usb_camera.py, run the following command:

nano opencv_test_usb_camera.py

Copy the code to your newly created file:

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/set-up-usb-camera-opencv-raspberry-pi/

import cv2

video_capture = cv2.VideoCapture(0)

while True:
    result, video_frame = video_capture.read()  # read frames from the video
    if result is False:
        break  # terminate the loop if the frame is not read successfully

    cv2.imshow(
        "USB Camera Test", video_frame
    )

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

video_capture.release()
cv2.destroyAllWindows()

View raw code

You need to change the id of the VideoCapture(id) to the one you’ve found in the previous section. In our case, the camera id is 0 and it looks as follows:

video_capture = cv2.VideoCapture(0)

Once you’ve made all the changes, press Ctrl+X to save your file, type Y and Enter.

Raspberry Pi OpenCV Python script edit device capture id

How the Script Works

Let’s take a quick look at how the code works. Start by importing the OpenCV library.

import cv2

Create a cv2.VideoCapture(0) object with your USB’s camera id called video_capture.

video_capture = cv2.VideoCapture(0)

Create a loop that keeps capturing new frames from the USB camera and displays them in the preview window. You can also stop the script at any time by pressing the q key on your keyboard.

while True:
    result, video_frame = video_capture.read()  # read frames from the video
    if result is False:
        break  # terminate the loop if the frame is not read successfully

    cv2.imshow(
        "USB Camera Test", video_frame
    )

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

When you stop the Python script it will stop the USB camera and close all the preview windows.

video_capture.release()
cv2.destroyAllWindows()

With your OpenCV Python environment activated, in our case:

source projectsenv/bin/activate

Start your script by running the following command:

python opencv_test_usb_camera.py
Raspberry Pi OpenCV run test USB camera Python script

A preview window opens and the webcam will be streaming in your Raspberry Pi desktop.

Raspberry Pi OpenCV test USB camera webcam

Troubleshooting

It might be a bit tricky to set up your USB camera, so we’ve compiled a list with 3 common issues that you might encounter and how to fix them.

Wrong Camera ID

If your camera fails to start, you might be using the wrong camera id. You can try the second listed /dev/video option, in our case 1.

/dev/video1
Raspberry Pi list all USB devices try different id for webcam

Then, pass 1 as the camera id in the video capture initialization and run the script again.

video_capture = cv2.VideoCapture(1)

Low Voltage

If you see the following message “Low voltage warning” at the top right corner of your Raspberry Pi Desktop, you might be using a power adapter that doesn’t provide enough power for the USB camera to run properly. Try to use a new power adapter that can provide enough power for your Raspberry Pi and camera.

Raspberry Pi low voltage warning check power supply

USB Camera is not Compatible

As we’ve mentioned earlier, some USB cameras might not be compatible with the Raspberry Pi OS due to driver incompatibilities. That’s why we recommend using a webcam from a well-known brand like Logitech to prevent driver issues.

Wrapping Up

In this quick guide, you learned how to set up a USB camera for your OpenCV projects with the Raspberry Pi. This will be useful for future OpenCV projects like face recognition, object detection, gesture detection, and more.

We hope you’ve found this tutorial useful. You can check all our Raspberry Pi projects on the following link:



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

2 thoughts on “Set Up USB Camera for OpenCV Projects with Raspberry Pi”

  1. Hello Ruiz,

    thank you very much for covering USB-cams on the Pi.

    Im using them for years taking meter readings (gas, electricity and water) using the tools provided by the OS-version used, so not using OpenCV.

    However, so far I was not able to manage to optically grab the actual meter readings, as numbers.

    Some folks claim to get it work using

    “ESP32-Cam on your water meter with “AI-on-the-edge” — also for gas and power meters”

    Well, if that`s the case, a Pi using OpenCV and Tesseract should do it as well. However, each kind of meter-displays have there own difficulties, especially water meters. Gas-Meters are best, then electric meter (Ferraris-Type), water-meters are the worst.

    Many Gas-Meters have a pulse count, so you could use it (however the actual reading is preferrable). Ferraris-Counter could be equipped with a puls count also.

    So a working Pi project for meter reading would be just great.

    Thanks

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.