How to install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster

How to install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster

In this tutorial you will learn how to install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster.

You will learn how to install OpenCV 4 on Raspbian Buster via both:

  1. A simple pip-install method (which can be completed in a matter of minutes)
  2. *Compiling from source *(which will take longer but will give you access to the full, optimized install of OpenCV)

To learn more about installing OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster, just keep reading.

Install OpenCV 4 on Raspberry Pi 4 and Raspbian Buster

In this tutorial we will install and test OpenCV 4 on *Raspbian Buster *in five simple, easy-to-follow steps.

If you’ve ever compiled OpenCV from scratch before, you know that the process is especially time-consuming and even painstakingly frustrating if you miss a key step or if you are new to Linux and Bash.

Installing OpenCV via pip is easier than ever. In fact, you can be up and running (Step #1 – Step #4a) in less than 10 minutes.

But what’s the catch?

Using pip to install OpenCV is great, but for some projects (including many educational projects on and in my books/courses) you might want the complete install of OpenCV (which the pip install won’t give you).

Don’t worry, I’ve got you covered in Step #4b below — you’ll learn to use CMake and Make to compile OpenCV 4 on BusterOS from scratch.

Let’s dive in!

Before we begin: Grab your Raspberry Pi and flash BusterOS to your microSD

Let’s review the hardware requirements for this tutorial:

  • Raspberry Pi: Despite the title of this tutorial, you may use the Raspberry Pi hardware including 3B, 3B+, or 4B to install OpenCV 4. These instructions only apply to Raspbian Buster, however.
  • 32GB microSD: I recommend the high-quality SanDisk 32GB 98Mb/s cards. Here’s an example on Amazon (however you can purchase them on your favorite online distributor).
  • microSD adapter: You’ll need to purchase a microSD to USB adapter so you can flash the memory card from your laptop.

If you don’t already have a Raspberry Pi 4, I highly recommend CanaKits (which are available on Amazon) and directly through Canakit’s website. Most of their kits come with a Raspberry Pi, power adapter, microSD, microSD adapter, heatsinks, and more!

install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster Figure 1: Hardware for installing OpenCV 4 on your Raspberry Pi 4 running Raspbian Buster.

Once you have the hardware ready, you’ll need to flash a fresh copy of the Raspbian Buster operating system to the microSD card.

  1. Head on over to the official BusterOS download page (Figure 2), and start your download. I recommend the “Raspbian Buster with Desktop and recommended software”.
  2. Download Balena Etcher — software for flashing memory cards. It works on every major OS.
  3. Use Etcher to flash BusterOS to your memory card (Figure 3).

install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster Figure 2: Download Raspbian Buster for your Raspberry Pi and OpenCV 4.

After downloading the Raspbian Buster .img file you can flash it to your micro-SD card using Etcher:

install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster Figure 3: Flash Raspbian Buster with Etcher. We will use BusterOS to install OpenCV 4 on our Raspberry Pi 4.

After a few minutes the flashing process should be complete — slot the micro-SD card into your Raspberry Pi 4 and then boot.

From there you can move on to the rest of the OpenCV install steps in this guide.

Step #1: Expand filesystem and reclaim space

For the remainder of this tutorial I’ll be making the following assumptions:

  1. You are working with a brand new, fresh install of Raspbian Buster (see the previous section to learn how to flash Buster to your microSD).
  2. You are comfortable with the command line and Unix environments.
  3. You have an SSH or VNC connection established with your Pi. Alternatively, you could use a keyboard + mouse + screen.

Go ahead and insert your microSD into your Raspberry Pi and boot it up with a screen attached.

Once booted, configure your WiFi/ethernet settings to connect to the internet (you’ll need an internet connection to download and install required packages for OpenCV).

From there you can use SSH as I have done, or go ahead and open a terminal.

The first step is to run, raspi-config and expand your filesystem:

$ sudo raspi-config

And then select the “7 Advanced Options” menu item:

install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster Figure 4: The raspi-config configuration screen for Raspbian Buster. Select 7 Advanced Options so that we can expand our filesystem.

Followed by selecting “A1 Expand filesystem”:

install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster Figure 5: The A1 Expand Filesystem menu item allows you to expand the filesystem on your microSD card containing the Raspberry Pi Buster operating system. Then we can proceed to install OpenCV 4.

Once prompted, you should select the first option, “A1 Expand File System”, hit enter on your keyboard, arrow down to the “” button, and then reboot your Pi — you may be prompted to reboot, but if you aren’t you can execute:

$ sudo reboot

After rebooting, your file system should have been expanded to include all available space on your micro-SD card. You can verify that the disk has been expanded by executing df -h and examining the output:

$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/root        29G  5.3G   23G  20% /
devtmpfs        1.8G     0  1.8G   0% /dev
tmpfs           1.9G     0  1.9G   0% /dev/shm
tmpfs           1.9G  8.6M  1.9G   1% /run
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/mmcblk0p1  253M   40M  213M  16% /boot
tmpfs           386M     0  386M   0% /run/user/1000

As you can see, my Raspbian filesystem has been expanded to include all 32GB of the micro-SD card.

However, even with my filesystem expanded, I have already used 15% of my 32GB card.

While it’s not required, I would suggest deleting both Wolfram Engine and LibreOffice to reclaim ~1GB of space on your Raspberry Pi:

$ sudo apt-get purge wolfram-engine
$ sudo apt-get purge libreoffice*
$ sudo apt-get clean
$ sudo apt-get autoremove

Step #2: Install dependencies

The following commands will update and upgrade any existing packages, followed by installing dependencies, I/O libraries, and optimization packages for OpenCV:

The first step is to update and upgrade any existing packages:

$ sudo apt-get update && sudo apt-get upgrade

We then need to install some developer tools, including CMake, which helps us configure the OpenCV build process:

$ sudo apt-get install build-essential cmake pkg-config

Next, we need to install some image I/O packages that allow us to load various image file formats from disk. Examples of such file formats include JPEG, PNG, TIFF, etc.:

$ sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng-dev

Just as we need image I/O packages, we also need video I/O packages. These libraries allow us to read various video file formats from disk as well as work directly with video streams:

$ sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
$ sudo apt-get install libxvidcore-dev libx264-dev

The OpenCV library comes with a sub-module named highgui which is used to display images to our screen and build basic GUIs. In order to compile the highgui module, we need to install the GTK development library and prerequisites:

$ sudo apt-get install libfontconfig1-dev libcairo2-dev
$ sudo apt-get install libgdk-pixbuf2.0-dev libpango1.0-dev
$ sudo apt-get install libgtk2.0-dev libgtk-3-dev

Many operations inside of OpenCV (namely matrix operations) can be optimized further by installing a few extra dependencies:

$ sudo apt-get install libatlas-base-dev gfortran

These optimization libraries are especially important for resource-constrained devices such as the Raspberry Pi.

The following pre-requisites are for Step #4a and they certainly won’t hurt for Step #4b either. They are for HDF5 datasets and Qt GUIs:

$ sudo apt-get install libhdf5-dev libhdf5-serial-dev libhdf5-103
$ sudo apt-get install libqtgui4 libqtwebkit4 libqt4-test python3-pyqt5

Lastly, let’s install Python 3 header files so we can compile OpenCV with Python bindings:

$ sudo apt-get install python3-dev

If you’re working with a fresh install of the OS, it is possible that these versions of Python are already at the newest version (you’ll see a terminal message stating this).

Step #3: Create your Python virtual environment and install NumPy

We’ll be using Python virtual environments, a best practice when working with Python.

A Python virtual environment is an isolated development/testing/production environment on your system — it is fully sequestered from other environments. Best of all, you can manage the Python packages inside your your virtual environment inside with pip (Python’s package manager).

Of course, there are alternatives for managing virtual environments and packages (namely Anaconda/conda). I’ve used/tried them all, but have settled on pip, virtualenv, and virtualenvwrapper as the preferred tools that I install on all of my systems. If you use the same tools as me, you’ll receive the best support from me.

You can install pip using the following commands:

$ wget
$ sudo python
$ sudo python3
$ sudo rm -rf ~/.cache/pip

Let’s install virtualenv and virtualenvwrapper now:

$ sudo pip install virtualenv virtualenvwrapper

Once both virtualenv and virtualenvwrapper have been installed, open up your ~/.bashrc file:

$ nano ~/.bashrc

…and append the following lines to the bottom of the file:

# virtualenv and virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /usr/local/bin/

install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster Figure 6: Using the nano editor to update ~/.bashrc with virtualenvwrapper settings.

Save and exit via ctrl + x , y , enter .

From there, reload your ~/.bashrc file to apply the changes to your current bash session:

$ source ~/.bashrc

Next, create your Python 3 virtual environment:

$ mkvirtualenv cv -p python3

Here we are creating a Python virtual environment named cv using Python 3. Going forward, I recommend Python 3 with OpenCV 4+.

Note: *Python 2.7 will reach end of its life on January 1st, 2020 so I *do not recommend using Python 2.7.

You can name the virtual environment whatever you want, but I use cv as the standard naming convention here on PyImageSearch.

If you have a Raspberry Pi Camera Module attached to your RPi, you should install the *PiCamera API *now as well:

$ pip install "picamera[array]"

Step #4(a or b): Decide if you want the 1-minute quick install or the 2-hour complete install

From here you need to make a decision about the rest of your install. There are two options.

  1. Step #4a: pip install OpenCV 4: If you decide to pip install OpenCV, you will be done in a matter of seconds. It is by far the fastest, easiest method to install OpenCV. It is the method I recommend for 90% of people — especially beginners. After this step, you will skip to Step #5 to test your install.
  2. Step #4b: Compile OpenCV 4 from source: This method gives you the full install of OpenCV 4. It will take 2-4 hours depending on the processor in your Raspberry Pi.

As stated, I highly encourage you to use the pip instructions. They are faster and will work for 90% of your projects. Additionally, the patented algorithms can only be used for educational purposes (there are plenty of great alternatives to the patented algorithms too).

Step #4a: pip install OpenCV 4

In a matter of seconds, you can pip install OpenCV into the cv virtual environment:

$ pip install opencv-contrib-python

install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster Figure 7: To quickly install OpenCV 4 on your Raspberry Pi 4 running Raspbian Buster, I recommend using pip as shown.

If you watch the terminal output of the above screenshot carefully you’ll see that OpenCV 3.4 rather than OpenCV 4 was installed?

What gives?

At the time of this writing, PiWheels has not been updated with pre-complied OpenCV 4 binaries for Raspbian Buster. PiWheels normally lags slightly behind the latest version of OpenCV, likely to ensure compatibility across the major Raspbian releases. Once OpenCV 4 has been released for PiWheels I will update this section.

That’s really all there is to it. You may skip to Step #5 now to test your install.

Step #4b: Compile OpenCV 4 from source

This option installs the full install of OpenCV including patented (“Non-free”) algorithms.

Note: Do not follow Step #4b if you followed Step #4a.

Let’s go ahead and download the OpenCV source code for both the opencv and opencv_contrib repositories, followed by unarchiving them:

$ cd ~
$ wget -O
$ wget -O
$ unzip
$ unzip
$ mv opencv-4.1.1 opencv
$ mv opencv_contrib-4.1.1 opencv_contrib

For this blog post, we’ll be using OpenCV 4.1.1; however, as newer versions of OpenCV are released you can update the corresponding version numbers.

Increasing your SWAP space

Before you start the compile you must increase your SWAP space. Increasing the SWAP will enable you to compile OpenCV with all four cores of the Raspberry Pi _(and _without the compile hanging due to memory exhausting).

Go ahead and open up your /etc/dphys-swapfile file:

$ sudo nano /etc/dphys-swapfile

…and then edit the CONF_SWAPSIZE variable:

# set size to absolute value, leaving empty (default) then uses computed value
#   you most likely don't want this, unless you have an special disk situation

Notice that I’m increasing the swap from 100MB to 1024MB. This is critical to compiling OpenCV with multiple cores on Raspbian Buster.

Save and exit via ctrl + x , y , enter .

$ sudo /etc/init.d/dphys-swapfile stop
$ sudo /etc/init.d/dphys-swapfile start

Compile and install OpenCV 4 on Raspbian Buster

We’re now ready to compile and install the full, optimized OpenCV library on the Raspberry Pi 4.

Ensure you are in the cv virtual environment using the workon command:

$ workon cv

Then, go ahead and install NumPy (an OpenCV dependency) into the Python virtual environment:

$ pip install numpy

And from there configure your build:

$ cd ~/opencv
$ mkdir build
$ cd build
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \

There are four CMake flags I’d like to bring to your attention:

  • (1) NEON and (2) VFPv3 optimization flags have been enabled. These lines ensure that you compile the fastest and most optimized OpenCV for the ARM processor on the Raspberry Pi (Lines 7 and 8).
    • Note: The Raspberry Pi Zero W hardware is not compatible with NEON or VFPv3. Be sure to remove Lines 7 and 8 if you are compiling for a Raspberry Pi Zero W.
  • (3) Patented “NonFree” algorithms give you the full install of OpenCV (Line 11).
  • And by drilling into OpenCV’s source, it was determined that we need the (4) -latomic shared linker flag (Line 12).

I’d like to take a second now to bring awareness to a common pitfall for beginners:

  • In the terminal block above, you change directories into ~/opencv/ .
  • You then create a build/ directory therein and change directories into it.
  • If you try to execute CMake without being in the ~/opencv/build directory, CMake will fail. Try running pwd to see which working directory you are in before running cmake . The cmake command will take about 3-5 minutes to run as it prepares and configures OpenCV for the compile. When CMake finishes, be sure to inspect the output of CMake under the Python 3 section:

install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster Figure 8: CMake configures your OpenCV 4 compilation from source on your Raspberry Pi 4 running Buster.

Notice how the Interpreter , Libraries , numpy , and packages path variables have been properly set. Each of these refers to our cv virtual environment.

Now go ahead and scroll up to ensure that the “Non-Free algorithms” are set to be installed:

install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster Figure 9: Installing OpenCV 4 with “Non-free algorithms” on Raspbian Buster.

As you can see, “Non-free algorithms” for OpenCV 4 will be compiled + installed.

Now that we’ve prepared for our OpenCV 4 compilation, it is time to launch the compile process using all four cores:

$ make -j4

install OpenCV 4 on the Raspberry Pi 4 and Raspbian Buster Figure 10: We used Make to compile OpenCV 4 on a Raspberry Pi 4 running Raspbian Buster.

Running make could take anywhere from 1-4 hours depending on your Raspberry Pi hardware (this tutorial is compatible with the Raspberry Pi 3B, 3B+, and 4). The Raspberry Pi 4 is the fastest at the time of this writing.

Assuming OpenCV compiled without error (as in my screenshot above), you can install your optimized version of OpenCV on your Raspberry Pi:

$ sudo make install
$ sudo ldconfig

Reset your SWAP

_Don’t forget to go back to your /etc/dphys-swapfile file and:

  1. Reset CONF_SWAPSIZE to 100MB.
  2. Restart the swap service.

Symbolic links are a way of pointing from one directory to a file or folder elsewhere on your system. For this sub-step, we will sym-link the bindings into your cv virtual environment.

Let’s proceed to create our sym-link. Be sure to use “tab-completion” for all paths below (rather than copying these commands blindly):

$ cd /usr/local/lib/python3.7/site-packages/cv2/python-3.7
$ sudo mv
$ cd ~/.virtualenvs/cv/lib/python3.7/site-packages/
$ ln -s /usr/local/lib/python3.7/site-packages/cv2/python-3.7/

Keep in mind that the exact paths may change and you should use “tab-completion”.

Step 5: Testing your OpenCV 4 Raspberry Pi BusterOS install

As a quick sanity check, access the cv virtual environment, fire up a Python shell, and try to import the OpenCV library:

$ cd ~
$ workon cv
$ python
>>> import cv2
>>> cv2.__version__

Congratulations! You’ve just installed an OpenCV 4 on your Raspberry Pi.


Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Create a Virtual Pen and Eraser with Python OpenCV - Genial Code

Learn Free how to create a virtual pen and eraser with python and OpenCV with source code and complete guide. This entire application is built fundamentally on contour detection. It can be thought of as something like closed color curves on compromises that have the same color or intensity, it's like a blob. In this project we use color masking to get the binary mask of our target color pen, then we use the counter detection to find the location of this pen and the contour to find it.

Keras vs. OpenCV - Differences Between Keras and OpenCV

Learn what is Keras and OpenCV with their applications. See Keras vs OpenCv to understand differences between OpenCv and keras for proper understanding.

Computer Vision for Dummies with OpenCV | OpenCV Tutorial

In this Computer Vision for Dummies with OpenCV, you will be working on an end-to-end project to understand computer vision. You will also be working on the basics of image processing with Python. We will also give you some ideas about OpenCV library basics and will do some practical task using OpenCV

OpenCV Python Tutorial: Computer Vision With OpenCV In Python

OpenCV Python Tutorial: Computer Vision With OpenCV In Python: Learn Vision Includes all OpenCV Image Processing Features with Simple Examples. Face Detection, Face Recognition. Computer Vision is an AI based, that is, Artificial Intelligence based technology that allows computers to understand and label images. Use OpenCV to work with image files. Create Face Detection Software. Detect Objects, including corner, edge, and grid detection techniques with OpenCV and Python. Use Python and Deep Learning to build image classifiers. Use Python and OpenCV to draw shapes on images and videos. Create Color Histograms with OpenCV

OpenCV Python Tutorial - Computer Vision With OpenCV In Python

In this OpenCV Python Tutorial article, we will be covering various aspects of Computer Vision using OpenCV in Python. OpenCV has been a vital part in the development of software for a long time. Learning OpenCV is a good asset to the developer to improve aspects of coding and also helps in building a software development career.