Title: Install OpenCV 4 on your Raspberry Pi - PyImageSearch

URL Source: https://pyimagesearch.com/2018/09/26/install-opencv-4-on-your-raspberry-pi/

Published Time: 2018-09-26T14:00:51+00:00

Markdown Content:
[![Image 1](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20400'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2018/08/install-opencv4-rpi-header.jpg)

Today I’m going to show you how to compile and install OpenCV 4 on your Raspberry Pi.

OpenCV 4 was [officially released](https://opencv.org/opencv-4-0-0.html) on November 20th, 2018.

This blog post was updated subsequently on November 28th to accommodate the changes to the install (previously these instructions linked to the alpha release source code).

It is also possible to [pip install OpenCV as well!](https://pyimagesearch.com/2018/09/19/pip-install-opencv/) As of this update however, PyPi does not contain precompiled OpenCV 4 binaries which can be installed via pip.

Therefore, if you want OpenCV 4 then you’ll need to compile from source.

**To learn how to install OpenCV 4 on your Raspberry Pi, _just follow this tutorial!_**

![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3C/svg%3E)

#### Looking for the source code to this post?

[Jump Right To The Downloads Section](#download-the-code)

In this blog post, we’re going to install OpenCV 4 on your Raspberry Pi. OpenCV 4 has a goal of reducing bloat, adding optimizations, and updating the deep learning module.

_**Note:**_ _There are many install guides on my blog. Before you begin, be sure to check out the available install tutorials on my **[OpenCV installation guides](https://pyimagesearch.com/opencv-tutorials-resources-guides/)** page._

First we’ll cover assumptions that go along with this tutorial.

From there, we’ll walk through 7 steps to compile and install OpenCV 4 on your Raspberry Pi. Compiling from source allows us to have full control over the compile and build. It also allows us to grab the latest code — something that pip and apt-get don’t offer.

Finally, we’ll test our OpenCV 4 install on our Raspberry Pi with a fun project.

Let’s get started.

### Assumptions

In this tutorial, I am going to assume that you already own a **[Raspberry Pi 3 B](https://amzn.to/2OzzWKi)** or the newer **[Raspberry Pi 3 B+](https://amzn.to/2xxGhOO)** with **[Raspbian Stretch installed](https://www.raspberrypi.org/downloads/raspbian/)**.

If you don’t already have the Raspbian Stretch OS, you’ll need to upgrade your OS to take advantage of [Raspbian Stretch’s new features](https://www.raspberrypi.org/blog/raspbian-stretch/).

To upgrade your Raspberry Pi 3 to Raspbian Stretch, you may [download it here](https://www.raspberrypi.org/downloads/raspbian/) and follow these [upgrade instructions](https://www.raspberrypi.org/documentation/installation/installing-images/README.md) (or [these for the NOOBS route](https://www.raspberrypi.org/downloads/noobs/) which is recommended for beginners). The former instructions take approximately 10 minutes to download via a torrent client and about 10 minutes to flash the SD card with Etcher or another tool. At that point you can power up and proceed to the next section.

Assuming that your OS is up to date, you’ll need one of the following for the remainder of this post:

*   _Physical access_ to your Raspberry Pi 3 so that you can open up a terminal and execute commands
*   _Remote access_ via SSH or VNC.

I’ll be doing the majority of this tutorial via SSH, but as long as you have access to a terminal, you can easily follow along.

_**Can’t SSH?**_ If you see your Pi on your network, but can’t ssh to it, you may need to enable SSH. This can easily be done via the Raspberry Pi desktop preferences menu (you’ll need an HDMI cable and a keyboard/mouse) or running `sudo service ssh start` from the command line of your Pi.

After you’ve changed the setting and rebooted, you can test SSH directly on the Pi with the localhost address. Open a terminal and type `ssh pi@127.0.0.1` to see if it is working. To SSH from another computer you’ll need the Pi’s IP address — you could figure it out by looking at your router’s clients page or by running `ifconfig` on the Pi itself.

_**Keyboard layout giving you problems?**_ Change your keyboard layout by going to the Raspberry Pi desktop preferences menu. I use the standard US Keyboard layout, but you’ll want to select the one appropriate for you.

### Step #1: Expand filesystem on your Raspberry Pi

To get the OpenCV 4 party started, fire up your Raspberry Pi and open an SSH connection (alternatively use the Raspbian desktop with a keyboard + mouse and launch a terminal).

Are you using a _brand new_ install of Raspbian Stretch?

If so, the first thing you should do is expand your filesystem to include _all available space_ on your micro-SD card:

$ sudo raspi-config

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

[![Image 3](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20453'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2018/08/install-opencv4-rpi-raspiconfig.jpg)

**Figure 1:** Selecting the “Advanced Options” from the `raspi-config` menu to expand the Raspbian file system on your Raspberry Pi is important before installing OpenCV 4. Next we’ll actually expand the filesystem.

Followed by selecting _“Expand filesystem”_:

[![Image 4](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20453'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2018/08/install-opencv4-rpi-expandfs.jpg)

**Figure 2:** The Raspberry Pi “Expand Filesystem” menu allows us to take advantage of our entire flash memory card. This will give us space necessary to install OpenCV 4 and other packages.

Once prompted, you should select the first option, _**“A1. Expand File System”**_, _**hit Enter**_ on your keyboard, arrow down to the _**“<Finish>”**_ 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        30G  4.2G   24G  15% /
devtmpfs        434M     0  434M   0% /dev
tmpfs           438M     0  438M   0% /dev/shm
tmpfs           438M   12M  427M   3% /run
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           438M     0  438M   0% /sys/fs/cgroup
/dev/mmcblk0p1   42M   21M   21M  51% /boot
tmpfs            88M     0   88M   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.

If you are using an 8GB card you may be using close to 50% of the available space, so one simple thing to do is to delete both LibreOffice and Wolfram engine to free up some space on your Pi:

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

**After removing the Wolfram Engine and LibreOffice, _you can reclaim almost 1GB!_**

### Step #2: Install OpenCV 4 dependencies on your Raspberry Pi

From there, let’s update our system:

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

And then let’s install developer tools including [CMake](https://cmake.org/):

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

Next, let’s install a selection of image and video libraries — these are _critical_ to being able to work with image and video files:

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

From there, let’s install GTK, our GUI backend:

$ sudo apt-get install libgtk-3-dev

And now let’s install a package which may reduce pesky GTK warnings:

$ sudo apt-get install libcanberra-gtk\*

The asterisk will grab the ARM specific GTK.

Followed by installing two packages which contain numerical optimizations for OpenCV:

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

And finally, let’s install the Python 3 development headers:

$ sudo apt-get install python3-dev

Once you have all of these prerequisites installed you can move on to the next step.

### Step #3: Download OpenCV 4 for your Raspberry Pi

Our next step is to download OpenCV.

Let’s navigate to our home folder and download both [opencv](https://github.com/opencv/opencv) and [opencv\_contrib](https://github.com/opencv/opencv_contrib). The contrib repo contains extra modules and functions which we frequently use here on the PyImageSearch blog. **You should be installing the OpenCV library with the additional contrib modules as well.**

When you’re ready, just follow along to download both the `opencv` and `opencv_contrib` code:

$ cd ~
$ wget -O opencv.zip https://github.com/opencv/opencv/archive/4.0.0.zip
$ wget -O opencv\_contrib.zip https://github.com/opencv/opencv\_contrib/archive/4.0.0.zip

From there, let’s unzip the archives:

$ unzip opencv.zip
$ unzip opencv\_contrib.zip

I also like to rename the directories:

$ mv opencv-4.0.0 opencv
$ mv opencv\_contrib-4.0.0 opencv\_contrib

If you skip renaming the directories, don’t forget to update the CMake paths.

Now that `opencv` and `opencv_contrib` are downloaded and ready to go, let’s set up our environment.

### Step #4: Configure your Python 3 virtual environment for OpenCV 4

Let’s grab and install pip, a Python Package Manager.

To install pip, simply enter the following in your terminal:

$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python3 get-pip.py

#### Make use of virtual environments for Python development

If you aren’t familiar with virtual environments, please take a moment look at this [article on RealPython](https://realpython.com/blog/python/python-virtual-environments-a-primer/) or read the first half of the [this blog post on PyImageSearch](https://pyimagesearch.com/2016/05/02/accessing-rpi-gpio-and-gpio-zero-with-opencv-python/).

Virtual environments will allow you to run different versions of Python software in isolation on your system. Today we’ll be setting up just one environment, but you could easily have an environment for each project.

Let’s go ahead and install `virtualenv` and `virtualenvwrapper` now — they allow for Python virtual environments:

$ sudo pip install virtualenv virtualenvwrapper
$ sudo rm -rf ~/get-pip.py ~/.cache/pip

To finish the install of these tools, we need to update our `~/.profile` file (similar to `.bashrc` or `.bash_profile` ).

Using a terminal text editor such as `vi` /`vim` or `nano` , add the following lines to your `~/.profile` :

\# virtualenv and virtualenvwrapper
export WORKON\_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER\_PYTHON=/usr/bin/python3
source /usr/local/bin/virtualenvwrapper.sh

Alternatively, you can append the lines directly via bash commands:

$ echo -e "\\n# virtualenv and virtualenvwrapper" >> ~/.profile
$ echo "export WORKON\_HOME=$HOME/.virtualenvs" >> ~/.profile
$ echo "export VIRTUALENVWRAPPER\_PYTHON=/usr/bin/python3" >> ~/.profile
$ echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.profile

Next, source the `~/.profile` file:

$ source ~/.profile

#### Create a virtual environment to hold OpenCV 4 and additional packages

Now you’re at the point where you can create your OpenCV 4 + Python 3 virtual environment on your Raspberry Pi:

$ mkvirtualenv cv -p python3

This line simply creates a Python 3 virtual environment named `cv` .

You can (and should) name your environment(s) whatever you’d like — I like to keep them short and sweet while also providing enough information so I’ll remember what they are for. For example, I like to name my environments like this:

*   `py3cv4`
*   `py3cv3`
*   `py2cv2`
*   etc.

Let’s verify that we’re in the `cv` environment by using the `workon` command:

$ workon cv

[![Image 5](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20374'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2018/08/install-opencv4-rpi-workoncv.jpg)

**Figure 3:** The **`workon`** command is part of the **virtualenvwrapper** package and allows us to easily activate virtual environments. Here I’m activating the `cv` environment which we’ll install OpenCV 4 into on our Raspberry Pi.

#### Install NumPy

The first Python package and only OpenCV prerequisite we’ll install is NumPy:

$ pip install numpy

We can now prepare OpenCV 4 for compilation on our Raspberry Pi.

### Step #5: CMake and compile OpenCV 4 for your Raspberry Pi

For this step, we’re going to setup our compile with CMake followed by running `make` to actually compile OpenCV. This is the most time-consuming step of today’s blog post.

Navigate back to your OpenCV repo and create + enter a `build` directory:

$ cd ~/opencv
$ mkdir build
$ cd build

#### Run CMake for OpenCV 4

Now let’s run CMake to configure the OpenCV 4 build:

$ cmake -D CMAKE\_BUILD\_TYPE=RELEASE \\
    -D CMAKE\_INSTALL\_PREFIX=/usr/local \\
    -D OPENCV\_EXTRA\_MODULES\_PATH=~/opencv\_contrib/modules \\
    -D ENABLE\_NEON=ON \\
    -D ENABLE\_VFPV3=ON \\
    -D BUILD\_TESTS=OFF \\
    -D OPENCV\_ENABLE\_NONFREE=ON \\
    -D INSTALL\_PYTHON\_EXAMPLES=OFF \\
    -D BUILD\_EXAMPLES=OFF ..

_**Update 2018-11-27:** Notice the `-D OPENCV_ENABLE_NONFREE=ON` flag. Setting this flag with OpenCV 4 ensures that you’ll have access to SIFT/SURF and other patented algorithms._

**Be sure to update the above command to use the correct `OPENCV_EXTRA_MODULES_PATH` path. If you’re following along with this tutorial _exactly_ you should not need to update the path.**

Once CMake is finished, it’s important that you inspect the output. Your output should look similar to mine below:

[![Image 6](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20432'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2018/09/install-opencv4-rpi-nonfree.jpg)

**Figure 4:** Ensure that “Non-free algorithms” is set to “YES”. This will allow you to use patented algorithms such as SIFT/SURF for educational purposes.

[![Image 7](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20377'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2018/08/install-opencv4-rpi-cmake.jpg)

**Figure 5:** The CMake command allows us to generate build files for compiling OpenCV 4 on the Raspberry Pi. Since we’re using virtual environments, you should inspect the output to make sure that the compile will use the proper interpreter and NumPy.

Take a second now to ensure that the `Interpreter` points to the correct Python 3 binary. Also check that `numpy` points to our NumPy package which is installed _inside_ the virtual environment.

#### Increase the SWAP on the Raspberry Pi

Before you begin the compile I would suggest _**increasing your swap space**_. This will enable you to compile OpenCV with _**all four cores**_ of the Raspberry Pi without the compile hanging due to memory exhausting.

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
# CONF\_SWAPSIZE=100
CONF\_SWAPSIZE=2048

Notice that I’m **increasing the swap from 100MB to 2048MB.**

_**If you do not perform this step it’s very likely that your Pi will hang.**_

From there, restart the swap service:

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

_**Note:** Increasing swap size is a great way to burn out your Raspberry Pi microSD card. Flash-based storage have limited number of writes you can perform until the card is essentially unable to hold the 1’s and 0’s anymore. We’ll only be enabling large swap for a short period of time, so it’s not a big deal. Regardless, be sure to backup your `.img` file after installing OpenCV + Python just in case your card dies unexpectedly early. You can read more about large swap sizes corrupting memory cards on [this page](https://www.bitpi.co/2015/02/11/how-to-change-raspberry-pis-swapfile-size-on-rasbian/)._

#### Compile OpenCV 4

Now we’re ready to compile OpenCV 4:

$ make -j4

_**Note:** In the `make` command above, the `-j4` argument specifies that I have 4 cores for compilation. **If you have compile errors or your Raspberry Pi hangs/freezes** you can try without the `-j4` switch which can eliminate race conditions._

Here you can see OpenCV 4 has compiled without any errors:

[![Image 8](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20402'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2018/09/install-opencv4-rpi-makeinstall.jpg)

**Figure 6:** I’ve compiled OpenCV 4 on my Raspberry Pi successfully (the `make` command has reached 100%). So now I’ll issue the `sudo make install` command.

And from there, let’s install OpenCV 4 with two additional commands:

$ sudo make install
$ sudo ldconfig

_**Don’t forget to go back**_ to your `/etc/dphys-swapfile` file and:

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

### Step #6: Link OpenCV 4 into your Python 3 virtual environment

Let’s create a symbolic link from the OpenCV install in the system `site-packages` directory to our virtual environment:

$ cd ~/.virtualenvs/cv/lib/python3.5/site-packages/
$ ln -s /usr/local/python/cv2/python-3.5/cv2.cpython-35m-arm-linux-gnueabihf.so cv2.so
$ cd ~

I cannot stress this step enough — **this step is _critical._** If you don’t create a symbolic link, you won’t be able to import OpenCV in your scripts. Also, ensure that the paths and filenames in the above commands are correct for your Raspberry Pi. **I suggest tab-completion.**

### Step #7: Test your OpenCV 4 install on your Raspberry Pi

Let’s do a quick sanity test to see if OpenCV 4 is ready to go.

Open a terminal and perform the following:

$ workon cv
$ python
>>> import cv2
>>> cv2.\_\_version\_\_
'4.0.0'
>>> exit()

The first command activates our virtual environment. Then we run the Python interpreter associated with the environment.

If you see that you have version 4.0.0 installed, then you’re now fully armed and dangerous + ready to perform computer vision and image processing.

### A Raspberry Pi + OpenCV 4 project to get your feet wet

A while back, I was working hard on responding to PyImageSearch readers via comments, emails, and Twitter/Facebook/LinkedIn. I make a point of responding to as many incoming questions and comments as I can.

It was 4:30 in the afternoon and I was cranking away at the keyboard in a “flow” state.

But while I was typing away, something triggered in my brain that I was thirsty. Very thirsty.

So I took a quick break from the keyboard and went to the fridge to grab a tasty beer ?.

**WTF?**

All my beers were gone!

Who stole my beer?!

I grabbed some water instead and went back to the computer. I closed all correspondence windows and fired up a code editor/IDE ([I like PyCharm](https://pyimagesearch.com/2015/08/17/the-perfect-computer-vision-environment-pycharm-opencv-and-python-virtual-environments/)).

I started tapping away at the keyboard again and sipping some water.

**What was I building?**

I was building a **security cam with my Raspberry Pi** which will catch people leaving/entering my apartment and opening/closing my fridge. I’ll catch that SOB stealing my beer next time!

[![Image 9](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20375'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/05/pi_home_surveillance_animated.gif)

**Figure 7:** Examples of the Raspberry Pi home surveillance system detecting motion in video frames and uploading them to my personal Dropbox account.

If you want to learn how to build a security camera with your Raspberry Pi and OpenCV 4, then I suggest you read the **[original blog post](https://pyimagesearch.com/2015/06/01/home-surveillance-and-motion-detection-with-the-raspberry-pi-python-and-opencv/)**.

This project is relatively simple and will accomplish the following:

*   Detects motion via background subtraction.
*   Uploads images of intruders and other motion to Dropbox so you can review events later. All images are timestamped so you’ll know when someone was in view of your Raspberry Pi security camera.

Or if you’re savvy and want to grab the code right now, you can be up and running in a few moments after you paste your Dropbox API key in the config file.

To download this project, scroll to the _**“Downloads”**_ section of this blog post and fill out the form.

You can download the zip to your `~/Downloads` folder and then fire up a terminal:

$ cd ~/Downloads
$ scp pi-home-surveillance.zip pi@192.168.1.119:~ # replace IP with your Pi's IP
$ ssh pi@192.168.1.119 # replace with your Pi's IP

Once your SSH connection is established let’s install a couple packages, namely the Dropbox API:

$ workon cv
$ pip install dropbox
$ pip install imutils
$ pip install "picamera\[array\]"

From there, unzip the files and change working directory:

$ cd ~
$ unzip pi-home-surveillance.zip
$ cd pi-home-surveillance

You’ll be presented with a directory structure that looks like this:

$ tree --dirsfirst
.
├── pyimagesearch
│   ├── \_\_init\_\_.py
│   └── tempimage.py
├── conf.json
└── pi\_surveillance.py

1 directory, 6 files

Before you’ll be able to deploy the project, you need to edit the config file, `conf.json` . Let’s quickly inspect it in our terminal using the `nano` text editor (or `vim` /`emacs` if you prefer):

$ nano conf.json

You’ll be presented with a JSON dictionary that looks like this:

[![Image 10](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20453'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2018/08/install-opencv4-rpi-seccam-conf.jpg)

**Figure 8:** The Raspberry Pi security camera configuration file. An API key must be pasted in, and a base path must be configured. For headless mode, “show\_video” should be set to “false”.

**At this point it is important to edit the configuration file with your API key and Path**. To find your API key, you can create an app on the [app creation page](https://www.dropbox.com/developers/apps/create). Once you have an app created, the API key may be generated under the OAuth section of the app’s page on the [App Console](https://www.dropbox.com/developers/apps) (simply click the “Generate” button and copy/paste the key into the configuration file). The Path needs to be a valid path in your Dropbox file structure.

_**Note:**_ _Don’t share your API key with anyone unless you trust them!_

For testing, you can leave `"show_video": true` and connect an HDMI screen + keyboard/mouse to your Pi. Eventually you’ll want to set the value to `false` and have your Pi run headless with few cables connected to it so you can hide it in the inconspicuously.

Once you get your project working, you can monitor the Dropbox folder in your web browser (you might need to refresh to check for images), or if you are syncing the folder to your laptop/desktop, you can monitor the folder there.

**I _highly recommend_ that you read the [entire blog post](https://pyimagesearch.com/2015/06/01/home-surveillance-and-motion-detection-with-the-raspberry-pi-python-and-opencv/) as well.**

Happy hacking with your Raspberry Pi and OpenCV 4!

### Troubleshooting and Frequently Asked Questions (FAQ)

Did you encounter an error installing OpenCV 4 on your Raspberry Pi?

**Don’t throw the little gadget across the room yet.** The first time you install OpenCV on your Raspberry Pi, it can be very frustrating and the last thing I want for you to do is to end the learning process here.

If you really get stuck, _don’t forget_ that the _**QuickStart Bundle**_ of **[_Practical Python and OpenCV + Case Studies_](https://pyimagesearch.com/practical-python-opencv/)** comes with Raspberry Pi images which are pre-configured and ready to go. Images for RPi 3B/3B+ and RPi Zero W are included. These images can save you hours and days (yes it took me about _6 days_ to set up the RPi Zero W) of frustration.

If you have your heart set on figuring this out on your own, I’ve put together a short list of frequently asked questions (FAQs) and I suggest that you familiarize yourself with them.

_**Q.**_ How do I flash an operating system on to my Raspberry Pi memory card?

_**A.**_ I recommend that you:

*   Grab a 16GB or 32GB memory card.
*   Flash Raspbian Stretch with Etcher to the card. Etcher is supported by all 3 major OSes.
*   Insert the card into your Raspberry Pi and begin with _“Assumptions”_ and _“Step 1”_ in this blog post.

_**Q.**_ Can I use Python 2.7?

_**A.**_ I don’t recommend using Python 2.7 as it’s rapidly approaching its end of life. Python 3 is the standard now. But if you insist…

Here’s how to get up and running with Python 2.7:

$ sudo apt-get install python2.7 python2.7-dev

Then, before you create your virtual environment in **Step #4**, first install pip for Python 2.7:

$ sudo python2.7 get-pip.py

Also in **Step #4**: when you create your virtual environment, simply use the relevant Python version flag:

$ mkvirtualenv cv -p python2.7

From there everything should be the same.

_**Q.**_ Can I just [pip to install OpenCV 4?](https://pyimagesearch.com/2018/09/19/pip-install-opencv/)

_**A.**_ In the future, yes. Currently you’ll need to compile from source until piwheels has an OpenCV 4 binary available.

_**Q.**_ Why can’t I just apt-get install OpenCV?

_**A.**_ Avoid this “solution” _at all costs_ even though it _might_ work. First, this method likely won’t install OpenCV 4 for a while. Secondly, apt-get doesn’t play nice with virtual environments and you won’t have control over your compile and build.

_**Q.**_ The  `mkvirtualenv`  and `workon` commands yield a “command not found error”. I’m not sure what to do next.

_**A.**_ There a number of reasons why you would be seeing this error message, all of come from to **Step #4:**

1.  First, ensure you have installed `virtualenv`  and `virtualenvwrapper`  properly using the `pip`  package manager. Verify by running `pip freeze` , and ensure that you see both `virtualenv`  and `virtualenvwrapper`  in the list of installed packages.
2.  Your `~/.profile`  file may have mistakes. View the contents of your `~/.profile`  file to see the proper `export`  and `source`  commands are present (check **Step #4** for the commands that should be appended to `~/.profile` ).
3.  You might have forgotten to `source`  your `~/.profile` . Make sure you run `source ~/.profile`  after editing it to ensure you have access to the `mkvirtualenv`  and `workon`  commands.

_**Q.**_ When I open a new terminal, logout, or reboot my Raspberry Pi, I cannot execute the `mkvirtualenv`  or `workon`  commands.

_**A.**_ If you’re on the Raspbian desktop, this will likely occur. The default profile that is loaded when you launch a terminal, for some reason, doesn’t source the `~/.profile`  file. Please refer to **#2** from the previous question. Over SSH, you probably won’t run into this.

_**Q.**_ When I try to import OpenCV, I encounter this message: `Import Error: No module named cv2` .

_**A.**_ There are _several_ reasons this could be happening and unfortunately, it is hard to diagnose. I recommend the following suggestions to help diagnose and resolve the error:

1.  Ensure your `cv`  virtual environment is active by using the `workon cv`  command. If this command gives you an error, then verify that `virtualenv`  and `virtualenvwrapper`  are properly installed.
2.  Try investigating the contents of the `site-packages`  directory in your `cv`  virtual environment. You can find the `site-packages`  directory in `~/.virtualenvs/cv/lib/python3.5/site-packages/`  depending on your Python version. Make sure (1) there is a `cv2`  sym-link directory in the `site-packages`  directory and (2) it’s properly sym-linked.
3.  Be sure to check the `site-packages`  (and even `dist-packages` ) directory for the system install of Python located in `/usr/local/python/` , respectively. Ideally, you should have a `cv2`  directory there.
4.  As a last resort, check in your `build/lib`  directory of your OpenCV build. There _should_ be a `cv2`  directory there (if both `cmake`  and `make`  executed without error). If the `cv2`  directory is present, _manually copy it_ into `/usr/local/python`  and then link the .so file to the `site-packages`  directory for the `cv`  virtual environment.

_**Q:**_ Why do I encounter a message about “Non-free modules” not being installed? How can I get the OpenCV non-free modules?

_**A:**_ New in OpenCV 4, a special CMake flag must be set to obtain the non-free modules.  Refer to **Step #5** above and pay attention to the flag in the CMake command.

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled

**I strongly believe that if you had the right teacher you could _master_ computer vision and deep learning.**

Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s _not_ the case.

All you need to master computer vision and deep learning is for someone to explain things to you in _simple, intuitive_ terms. _And that’s exactly what I do_. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to _successfully_ and _confidently_ apply computer vision to your work, research, and projects. Join me in computer vision mastery.

**Inside PyImageSearch University you'll find:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ hours** of on-demand video
*   ✓ **Brand new courses released _regularly_**, ensuring you can keep up with state-of-the-art techniques
*   ✓ **Pre-configured Jupyter Notebooks in Google Colab**
*   ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
*   ✓ Access to **centralized code repos for _all_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

Summary
-------

Today we installed OpenCV 4 on our Raspberry Pi.

Compiling from source was paramount so that we could obtain OpenCV 4 since it isn’t possible yet to install OpenCV 4 via pip.

We then tested our install and deployed a Raspberry Pi as a security camera. This security camera will detect motion via background subtraction and upload pictures of intruders to Dropbox. [You can read the full Raspberry Pi + home surveillance post here.](https://pyimagesearch.com/2015/06/01/home-surveillance-and-motion-detection-with-the-raspberry-pi-python-and-opencv/)

**To stay up to date with PyImageSearch, _be sure to drop your email in the form below!_**

![Image 11](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### Download the Source Code and FREE 17-page Resource Guide

Enter your email address below to get a .zip of the code and a **FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.** Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!