Install OpenCV 4 on your Raspberry Pi

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

OpenCV 4 is currently in alpha-release status, but that doesn’t mean you shouldn’t try out some of the new features and optimizations before they put the official stamp on it.

Once OpenCV 4 is released I’ll show you how to pip install OpenCV as well!

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

Looking for the source code to this post?
Jump right to the downloads section.

Install OpenCV 4 on your Raspberry Pi

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 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.

Furthermore, since OpenCV 4 is still in pre-release you cannot pip install OpenCV. And even when OpenCV 4 is officially released, you’ll still need to wait for PiWheels to create the latest distribution. Compiling by source ensures you always have the latest and greatest.

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 or the newer Raspberry Pi 3 B+ with Raspbian Stretch installed.

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.

To upgrade your Raspberry Pi 3 to Raspbian Stretch, you may download it here and follow these upgrade instructions (or these for the NOOBS route 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:

And then select the “Advanced Options” menu item:

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”:

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:

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:

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:

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:

And then let’s install developer tools including CMake:

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

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

And now let’s install libcanberra  — it may reduce pesky GTK warnings:

The asterisk will grab the ARM specific GTK.

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

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

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 and 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:

From there, let’s unzip the archives:

I also like to rename the directories:

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:

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 or read the first half of the this blog post on PyImageSearch.

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:

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 :

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

Next, source the ~/.profile  file:

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:

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:

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:

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:

Run CMake for OpenCV 4

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

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:

Figure 4: 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:

…and then edit the CONF_SWAPSIZE  variable:

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

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

From there, restart the swap service:

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.

Compile OpenCV 4

Now we’re ready to compile OpenCV 4:

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:

Figure 5: 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:

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:

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:

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

Note: It is not necessary to specify python3  as Python 3 is the only Python executable in the environment.

Figure 6: OpenCV 4 has been installed on our Raspberry Pi as is verified in the terminal Python interpreter.

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).

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!

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.

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:

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

From there, unzip the files and change working directory:

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

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):

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

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. 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 (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.

highly recommend that you read the entire blog post 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 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 approach 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:

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

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

From there everything should be the same.

Q. Can I just pip to install OpenCV 4?

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.so  file in the  site-packages  directory and (2) it’s properly sym-linked to a valid file.
  3. Be sure to check the site-packages  (and even dist-packages ) directory for the system install of Python located in /usr/local/lib/python3.5/site-packages/ , respectively. Ideally, you should have a cv2.so  file there.
  4. As a last resort, check in your build/lib  directory of your OpenCV build. There should be a cv2.so  file there (if both cmake  and make  executed without error). If the cv2.so  file is present, manually copy it into both the system site-packages  directory as well as the site-packages  directory for the cv  virtual environment.

Q. What if my question isn’t listed here?

A. Please leave a comment below or send me an email. If you post a comment below, just be aware that code doesn’t format well in the comment form and I may have to respond to you via email instead.

Summary

Today we installed OpenCV 4 on our Raspberry Pi.

Compiling from source was paramount so that we could obtain the OpenCV 4 pre-release source code.

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.

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

Downloads:

If you would like to download the code and images used in this post, please enter your email address in the form below. Not only will you get a .zip of the code, I’ll also send you 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! Sound good? If so, enter your email address and I’ll send you the code immediately!

, , , ,

49 Responses to Install OpenCV 4 on your Raspberry Pi

  1. Sudeep September 26, 2018 at 11:09 am #

    Hey Adrian, How come we dis not need to change the Swap size from the default 100 to the 1024 like we did in the other OpenCV installs on the Rpi

    • David Hoffman September 26, 2018 at 12:49 pm #

      Hi Sudeep, good catch. It is very important to change the SWAP to 1024 before starting the compile. I made this change for Adrian while he is on vacation.

  2. marco September 26, 2018 at 12:47 pm #

    Hello Adrian, I followed step by step your beautiful post and everything went smoothly up to the Cmake -D where in the end I received an error, thinking it was not very important I continued the installation but when I typed Make -j4 not the He found … where did I go wrong?

    (cv) pi@raspberrypi: ~/opencv-4.0.0-alpha/build $ make -j4
    make: *** No specified target and no makefiles found. Stop."

    • David Hoffman September 26, 2018 at 1:10 pm #

      Hi Marco, this is because you did not rename your directories as specified in Step #3. It isn’t your fault — due to OpenCV 4 Alpha releasing on September 20th while Adrian was on vacation, and considering Adrian wrote this post about 3 weeks ago, this post needed a last minute update (from cloning the Git repo to downloading the zip archives). I updated the post to show the need for renaming the directories. Simply rename your opencv-4.0.0-alpha directory to opencv and opencv_contrib-4.0.0-alpha to opencv_contrib. Then delete the build directory and re-run CMake and continue to follow the instructions. Sorry for the mixup and thanks for bringing it to our attention!

  3. Linus Goh September 26, 2018 at 3:25 pm #

    Hi Adrian, David,

    I’m an active member of the Raspberry Pi community so I think I can say a word or two about that 🙂

    1. Step #1 should NOT be necessary, as Raspbian will do this step *automatically* on the first boot and reboot afterwards, which is since a long time BTW. Even though it might not yield any errors doing it a second time, I see no improvement in it, whatsoever.

    2. Even though recommended by the foundation itself, in the German Raspberry Pi forum we have commonly reports of strange issues caused by NOOBS installs of Raspbian which DO NOT OCCUR when doing a direct flashing of Raspbian onto the SD card, with the same Pi, PSU etc.
    It’s not entirely clear what causes this, but IMO NOOBS is to be recommended with caution, especially to completely new users. They should be able to use Raspbian installed directly as it’s the next step after NOOBS for most people anyway.

    Cheers!

    • Abhishek Thanki September 27, 2018 at 10:17 am #

      Hi Linus,

      Interesting on Raspbian automatically expanding the filesystem. I recently did an install and had to do it manually.

      Also, I think the only reason why Adrian recommends NOOBS for beginners is since it’s recommended by the foundation itself. But thanks for your input on it!

      • Alexander Holsgrove September 28, 2018 at 1:06 pm #

        I think if you’re interested in learning about OpenCV and other articles by Adrian, then you’re probably more likely to be comfortable working on Raspbian rather than NOOBS!

  4. Johan Smit September 27, 2018 at 12:46 am #

    Hi,
    I have done embedded work on Arm processors (STM32F1 and F4) in C without operating system, but no Raspberry Pi.
    Please help me with information.
    I would like to use the unit as a type of trail camera, with animal recognition and discarding some photos but saving others according to type of animal.
    This means that the processor must mostly sleep, and be woken up by passive infrared detector.
    The question is: Will the Raspbian operating system be able to handle this wakeup to take photos in a short time, eg., milliseconds?
    I have seen Raspberry Pis boot up, and that is totally useless, minutes rather than milliseconds.
    Any information will be greatly appreciated, thank you
    Johan Smit

    • Denis Brion September 28, 2018 at 5:55 am #

      w/r to RPi starting in minutes : consider a RPi as … a PC (libreoffice, wolfram are x86 ports to ARMs) and notice it boots about 10 100 times faster than Windows (part of Windows booting is hidden : there is a desktop for marketing “reasons”, but difficult to use).
      There is a thing RPi is very bad: it is what PC have, named ACPI (ask wikipedia). RPi has no -or very lousy and buggy- sleep options. Do not worry : nanoPi (chinese “clones”, with better HW design, octo cores – are worse in this domain,… I am af asking a raid you asking a feature where RPis are at their worst.

  5. Denis Brion September 27, 2018 at 3:51 am #

    Three things worry me :

    a) make -j’ is unnecessary; make (without j) will compile 4 times slower… and keep RPi somewhat cool (BTW, at least in hot countries… or in summer, an heatsink+ fan are useful/necessary when compiling for hours)

    b) one can remove the tiny swap partition and add an external swap file on a USB disk.
    Drawbacks :it is slightly slower; one needs to compile linux-utils (IIRC) for a classical manipulation)
    Advantages : repeated writes on a flash device ruins it…. and swap is made to allow repeated writes. No need to remove libreoffice (suppose one needs it) or wolfram. One can get rid of the 100M nanoflash (eats a little disk swap).
    AFAIK (from reading last year dphys git) , dphys is a warpper around sawpon and swapoff… (parts of linux-utils: I prefer using century old commands to 1) make a swap file (not partition); 2) desctivate the 100 M builtin partition; 3) actvate the new swap file)

    c) alpha versions seem … very new. What is the advantage over a ocv3-x version (btw: pip installing a 3.x version worked very fast and comfortably, as you showed it last week)

    • Abhishek Thanki September 27, 2018 at 10:08 am #

      Hi Denis,

      a) I think using make -jx is a personal choice and I don’t really see any issues with it, most people would go for speed on any given day. (Also, having lived in a country where temperatures go upto 50C in summer, we use A/Cs, and it’s pretty cool inside. 🙂 )

      b) Interesting and theoretically speaking it makes sense. Definitely something worth a try.

      c) Advantages: optimizations, C++11 support, more compact modules, and many improvements to the Deep Neural Network (DNN) module.

      • Denis Brion September 29, 2018 at 8:56 am #

        Hi Abishek:
        heat issues are not a worry for computers between Syria and North India: as people know one can reach 50C, one has an air conditioner. OTOH, in West Europe, heath spells are rare enough, thus most people do not have air conditioners.
        I have a nanoPi m3 (octocore) and just an airshield -no fan : is noisy- and tried with 8 cores (compiling xtensa-gcc : does not need swap extension: it lasted 15 minuts with heatsink before crushing: using 3 cores was OK).

        nanoPi m3 are very much like RPi (less support; use debian stable instead of debian unstable ; software compiled on a nanoPi is likely to work -ocv does- once newer (but compatible) libraries are installed. same RAM -1G-: worse temperature scaling, IMO).
        I managed to have ocv4 alpha installed (had to remove _xfeatures2d and stiching, to avoid issues) using your script the following way:

        a) I made a huge (1G) file in ~/ext/catalogue/gros using dd.
        597 sudo mount /dev/sdb2 ext # ~ext is mount point /directory
        598 ls ext
        599 ls ext/catalogue

        609 dd if=/dev/zero of=ext/catalogue/gros bs=1k count=1024k
        610 sync
        611 ls -lh ext/catalogue/gros

        b) as “gros” cannot be used as a swap file as it is, it must be preapaired. single issue is that some parts of util-linux (ask wikipedia for util-linux)are not packaged , as, among them, the one I neded, mkswap, was not packaged -according to Murphys laws- and I had to compile them from sources (got from https://mirrors.edge.kernel.org/pub/linux/utils/util-linux/v2.15/) the following way:

        619 tar xvf cle/utilLinux.tar.gz
        620 cd util-linux-2.26-rc1/
        621 ./configure
        622 make -j4 # is short to compile… wonot heat that much
        623 ls # what did I do?
        624 ./mkswap ~/ext/catalogue/gros # no need to install, it is just to prepare a swap file

        Then, it is straight forwards (on a RPi, one should remove existing wap partition with suso swapoff -a )

        625 sudo swapon ~/ext/catalogue/gros
        626 history >~/swapstoria # to remember … for next time or pyimagesearch…

        Then, compilation (with one core enabled) was comfortable (almost no library needed swap : makes a difference with ocv3 IIRC and seems a nice side of ocv4; only one was python bindings which needed about 400 M swap + exiting RAM -but desktop remains usable for reading docs)

  6. Alexander Holsgrove September 28, 2018 at 1:03 pm #

    After running the build and then the make on a Raspberry Pi 3, I can’t link the .so file as it’s not there. I do have /usr/local/lib/python3.5/dist-packages/cv2.cpython-35m-arm-linux-gnueabihf.so and also /usr/local/lib/python3.5/dist-packages/cv2.cpython-35m-arm-linux-gnueabihf.so

    What have I done wrong please?

    • Adrian Rosebrock October 8, 2018 at 12:21 pm #

      You have not done anything wrong. Use the filename that you have found.

  7. Matteo September 29, 2018 at 1:45 am #

    Hello to all,
    I am a beginner and I have some problems with the translations, I tried to document before writing but probably it did not happen to anyone that after making make -j4 without errors and verified the correct directories of the python and Numpy interpreter launching the python command then gave “importError: no module named CV2”
    I think it’s a path problem, but I do not know how to get it back, can you help me?

    • Adrian Rosebrock October 8, 2018 at 12:18 pm #

      Hey Matteo, I would recommend you read the “Troubleshooting and Frequently Asked Questions (FAQ)” section of this tutorial as I provide answers to the most common reasons why you may not be able to import the OPenCV bindings.

  8. Alexander Holsgrove September 29, 2018 at 12:18 pm #

    The symlink was wrong for me. The file is “cv2.cpython-35m-arm-linux-gnueabihf.so” and not “cv2.cpython-35m-x86_64-linux-gnu.so”. The whole command therefor “ln -s /usr/local/lib/python3.5/site-packages/cv2.cpython-35m-arm-linux-gnueabihf.so cv2.so

  9. Pranav Lal September 30, 2018 at 12:42 am #

    Hi,
    I completed the installation. I had to interrupt make -j4 once when it was stuck at 99%. I ran make again without any parameters. I have followed the rest of the guide including creating the symbolic link. However, when I import cv2 python 3.5 is unable to find the file. I have created a virtual environment named cv4 and have followed the rest of your instructions without problems. What data should I share to help us diagnose the problem?

    • Adrian Rosebrock October 8, 2018 at 12:11 pm #

      Take a look at the “Troubleshooting and Frequently Asked Questions (FAQ)” section of this tutorial as I discuss the most common reasons why the import will fail.

  10. Cameron October 2, 2018 at 2:42 am #

    Hi,

    I have tried following this tutorial to compile opencv 4 for the orangepi zero board, however when I run the cmake command it does not complete due to errors. Looking in the error log it says:
    Regex: ‘command line option .* is valid for .* but not for C\+\+’

    Any ideas why this may be happening?

  11. marco October 2, 2018 at 2:44 am #

    hello Adrian, I would like to understand one thing, why on the Raspberry even if you follow the post to the letter then OpenCv does not install as it should, even repeating the installation several times then you always find yourself with the same problem! You know I thought maybe if you put a video with all the steps of the installation maybe it could help beginners like me to understand where have wrong or at least see where there are differences in the installation.

    However, I thank you because you are doing a great jo

    • Adrian Rosebrock October 8, 2018 at 10:40 am #

      I’ve done a few Raspberry Pi + OpenCV install guide videos. I’m considering doing one for this post as well but I wanted to wait until OpenCV 4 is officially released.

  12. Lee October 2, 2018 at 6:27 am #

    hi , have anyone of you here faced this problem?
    the build of opencv hang/not responding when come to 98% progress.
    any suggestion/comment?

    • Adrian Rosebrock October 8, 2018 at 10:35 am #

      Did you increase your swap size as recommended? If so, try:

      1. Deleting your “build” directory
      2. Re-creating your “build” directory
      3. Re-run “cmake”
      4. Start the compile but this time only compile with a single core via “make -j1”

      It sounds like your Pi is running into a threading/race condition which is causing the problem.

  13. Andrew Baker October 2, 2018 at 6:49 pm #

    I was able to successfully install OpenCV 4.4.0-alpha. However I had some initial issues.
    1. The first attempt failed, RPI locked up. I had the swap space at 1024MB and used the make -j4 command. While running the RPI was very hot (80 – 85C).

    2. I deleted my build folder and tried again. This time I was met with the error:
    cmake fails to determine the bitness of the target platform.

    Solution:.
    1. Within an old post I found a slightly different cmake command. This was the modified command I used:
    cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-4.0.0-alpha/modules \
    -D ENABLE_NEON=ON \
    -D ENABLE_VFPV3=ON \
    -D BUILD_TESTS=OFF \
    -D INSTALL_PYTHON_EXAMPLES=OFF
    -D CMAKE_SIZEOF_VOID_P=4 \
    -D BUILD_opencv_python3=TRUE \
    -D PYTHON3_LIBRARY=/usr/lib/arm-linux-gnueabihf/libpython3.5m.so \
    -D BUILD_EXAMPLES=OFF ..

    2. I executed this with only cmake. I didn’t use -j4.

    3. It took approximately 4 hours, but the build complied and installed successfully.

    • Adrian Rosebrock October 8, 2018 at 10:31 am #

      Thanks for sharing Andrew! And congrats on getting OpenCV 4 installed on your Pi.

  14. Gaurav Shirke October 3, 2018 at 1:27 am #

    [ 95%] Building CXX object modules/python2/CMakeFiles/opencv_python2.dir/__/src2/cv2.cpp.o

    stucked at 95%
    tried with make -j4 which stuck at same line but with 98%
    with makt -j1 at 95%
    and with make at 95%

    • Gaurav Shirke October 3, 2018 at 4:31 am #

      problem solved

      • Adrian Rosebrock October 8, 2018 at 9:15 am #

        Congrats on resolving the issue, Gaurav!

    • Adrian Rosebrock October 8, 2018 at 10:28 am #

      Did you increase your swap size like I recommended in the tutorial? Make sure you do so. Alternatively, you can pip install opencv.

  15. Gaurav Shirke October 3, 2018 at 4:30 am #

    eveything is okay but then this error occured
    ln: failed to create symbolic link ‘cv2.so’: File exists

    Followed all steps open cv2.so file is not there in ”/usr/local/lib/python3.5/site-packages/”

    another file is present their which is named as ”cv2.cpython-35m-arm-linux-gnueabihf.so”

  16. Arul October 3, 2018 at 7:36 am #

    Step # 6 references incorrect lib? I see only ARM version, not x86. I had to do this instead.

    ln -s /usr/local/lib/python3.5/site-packages/cv2.cpython-35m-arm-linux-gnueabihf.so cv2.so

    • Adrian Rosebrock October 8, 2018 at 10:25 am #

      Hey Arul, I’ve updated the tutorial with the path most readers are getting. I suggest other readers use tab completion to derive the correct file name.

  17. murksiuke October 5, 2018 at 3:25 am #

    hello, after the cmake the output shows the interpreter as python2.7, even though i followed the commands on the guide. not sure what to do

    • Adrian Rosebrock October 8, 2018 at 9:52 am #

      Are you referring to the interpreter used for the compile? If so, ignore it — that’s a bug in the “cmake” output. As long as your “Python 3” section looks like mine you can proceed.

      • murksiuke October 11, 2018 at 2:27 pm #

        Thank you for the reply, i redid the whole thing (actually got a larger sd because of space problems) and everything went fine. Thanks for the guide!

        • Adrian Rosebrock October 12, 2018 at 8:56 am #

          Fantastic, I’m glad it worked for you! 🙂

  18. Ahmed Raza October 5, 2018 at 5:04 am #

    having an error while cmake

    Run CMake for OpenCV 4

    configuration in complete, errors occured!

    • Adrian Rosebrock October 8, 2018 at 9:51 am #

      Take a look at your output of “cmake”. It will tell you what the error is.

  19. Francisco October 5, 2018 at 8:07 pm #

    Hi, thanks for the detailed tutorial.

    I faced an issue when creating the link in step #6, the output .so file had a different name “cv2.cpython-35m-arm-linux-gnueabihf.so” instead of “cv2.cpython-35m-x86_64-linux-gnu.so”, so I had to rename it (this was already pointed out in your previous tutorial for installing OpenCV 3).

    • Adrian Rosebrock October 8, 2018 at 9:48 am #

      Thanks Francisco. I’ve updated the post but I would encourage readers to use tab completion to correctly determine their output filename.

  20. Charlie October 8, 2018 at 1:24 pm #

    Hi Dr. Adrian. As a beginner, I wonder if it’s possible to have both versions of OpenCV (3.x and 4.x) installed on a Pi. Can I use a virtual environment (VE) for each version? If so, how can I do that? Is it covered in any blog post? Besides, how can I update an Environment with a more recently Python version when one becomes available? Can I do the same with a new OpenCV release in a VE? Thank you.

    • Adrian Rosebrock October 8, 2018 at 1:40 pm #

      Yes, you can have multiple OpenCV versions on your system. I like to:

      1. Create a new Python virtual environment for each version of OpenCV
      2. Compile OpenCV but only sym-link in the OpenCV bindings from the “build/lib” directory (I keep a “build” directory for each version of OpenCV I compile)

  21. Steven October 9, 2018 at 7:31 pm #

    Adrian

    Thank you for the post really appreciate it. I built OpenCV 4.0 on new Pi3 Model B+ booting off mSATA drive with you can do with the new Model B+. I was monitoring the build with -J4 switch with free -h and the process actually used up the swap file and stalled in latter stages of the build, (99% stage). Increased the swap size and was able to make it through that late build stage and complete. Its possible that some of the others reading the comments hit the same situation. Quick question why does your version show 4.0 and mine show 4.0 alpha on the check version?

    import cv2
    >>> cv2.__version__
    ‘4.0.0-alpha’
    >>> exit()

    • Adrian Rosebrock October 12, 2018 at 9:22 am #

      Hey Steven, thanks for the tip on increasing swap size further. Compiling only only a single core just should resolve the issue as well.

      Regarding your question, it looks like you compiled OpenCV using the official alpha version of the library. When I compiled OpenCV it was with the pre-release which did not have the “alpha” tag, hence the discrepancy.

  22. m October 11, 2018 at 2:24 pm #

    Hello! Is there a reason for installing inside the “cv” environment? I have seen guides that skip that step, and in the end you can call “import cv2” without a “workon cv” command beforehand.

    • Adrian Rosebrock October 12, 2018 at 8:56 am #

      Using Python virtual environments is a best practice in Python development. They are certainly optional but heavily recommended. If you’re new to Python virtual environments or how they work be sure to read this post.

  23. Phil Desrosiers October 16, 2018 at 1:25 am #

    I’m getting “zsh: no matches found: libcanberra-gtk*” when I try to apt-get libcanberra-gtk* .

    As far as I know, my sources are up to date. Do I need to add another apt source somewhere?

Leave a Reply