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 was officially released 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! 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!

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.

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

Let’s get started.


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@  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 a package which 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:

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:

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.

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:

…and then edit the CONF_SWAPSIZE  variable:

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:

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

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.

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


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

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

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.


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.

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


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!

, , , ,

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

      • Ted September 7, 2019 at 2:17 pm #

        Hi David.
        I did everything like this post and got no errors. But in the end it does not know workon cv.should I enter workon cv in a new terminal or the same I did installation. I examined in both.
        Please help me.
        Thank u

      • Ted September 7, 2019 at 2:20 pm #

        Raspberrypi downloded python 3.7 so should I change #step6

  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!

      • Filippo Pesavento December 1, 2018 at 8:24 am #

        Hi 🙂 I got the same error, though I renamed correctly all folders. Seems to be an error from the previous step, using cmake.
        Cmake does not say “Configuring done” and “Generating done”, but it throws an error log file and I cannot figure out why. Any suggestion?
        PS. I followed the tutorial step by step, even if I am very familiar with Linux and bash. I’m running the latest version of Raspbian Lite, if that can help.

        • pag August 6, 2019 at 12:26 pm #

          I have the same problem. Did anyone find a solution to this or can name the issue?

          • peru August 25, 2019 at 3:56 pm #

            Hi! as i faced this problem also, i found a solution that worked for me.
            i changed the -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \ with relative paths instead of the “~”. then the cmake process finishes with out any errors

            hope this helps

  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.


    • 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 #

    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 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/ and also /usr/local/lib/python3.5/dist-packages/

    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 “” and not “”. The whole command therefor “ln -s /usr/local/lib/python3.5/site-packages/

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

    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.

      • carlo santos March 25, 2019 at 8:44 pm #

        hi adrian how can i fix the error name module cv2, when i write the code $python, and type import cv2 the system will not determine the module name cv2 thanks alot

        • Adrian Rosebrock March 27, 2019 at 8:47 am #

          There are many reasons why that could happen. I have documented the most common reasons in the “Troubleshooting and Frequently Asked Questions (FAQ)” section of this post.

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


    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.

    • Chris Pinkenburg October 28, 2018 at 2:11 pm #

      Hi Lee,
      at the end of the compilation using -j4 you run two linking processes – each taking 80% of the available memory and the raspberry pi swaps itself to death achieving nothing (run “top” in a terminal window, hit M to sort by memory and you’ll see two large compilation processes which do not get any significant cpu).
      What worked for me is to ctrl-c the ongoing build and then run make without -j4. There is enough memory for running one process. You do not need to run a make clean, make will pick up where you left it. This way you still get the benefit of running -j4 which is a lot faster

  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.

    1. Within an old post I found a slightly different cmake command. This was the modified command I used:
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-4.0.0-alpha/modules \
    -D BUILD_opencv_python3=TRUE \
    -D PYTHON3_LIBRARY=/usr/lib/arm-linux-gnueabihf/ \

    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!

      • devashish October 27, 2018 at 10:14 am #

        same here . How did you do it?

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

    • Maciej Bartoszek February 1, 2019 at 10:06 am #

      hello Gaurav,
      got same problem here.
      How did you solve it?

      • Adrian Rosebrock February 5, 2019 at 9:46 am #

        Increase your swap size to 2048MB. Then compile with just “make” instead of “make -j4”

        • Sai April 6, 2019 at 10:15 pm #

          Hi Adrian,

          I followed all your steps until make -j4. It was stuck at 99% for a long time. Restarted make and now currently keeps stopping at 98% how many ever times I try. I have already increased the swap size to 2048MB. Please let me know if there is any other step i am missing.

          • Adrian Rosebrock April 12, 2019 at 12:51 pm #

            Try using only a single core for the compile via just “make” (no “-j4”).

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

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

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

    another file is present their which is named as ””

  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/

    • 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 “” instead of “”, 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. Adrian Rosebrock October 8, 2018 at 9:16 am #

    Thanks for sharing, Victor. I’ve updated the blog post. I also recommend readers perform tab completion so correctly determine the filename.

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

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


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

      • Denis Brion October 17, 2018 at 7:03 am #

        AFAIK :
        a) “only” last stage needs swaps, if one uses a single core (else, one has to add memory consumptions of each process + some RAM to have parallel processes to communicate)
        b) last stage is a single process build (makes a huge *.so with a lot of libraries, ready to be called by python): it needs less than 1G swap (total less than 2G RAM+ virtual RAM : if RPi had 2 G RAM, … no swap would be needed.

        Is it possible to … cross compile for RPi (I sometimes use nanoPi -debian stable- to make binaries for RPi -debian unstable-: *.so are compatible (the other way, it would not), though certain optimisations cannot be caught. Cross compiling goes further : one uses an x86 PC -some have tons of RAM, lets us say 4 G- to make *.so -and executables; they are sent to a RPi (arduino cross compiles for … avrs, say) : hertaville used it for <=512 M RPis
        It might be difficult to install on the first time, but much faster (and one often needs a PC … to put on a SD disk the Rapsbian image : at least, once…). (processes using swap have unpredictable delays : depends on the nature and state of the swap partition/file ; a process can be seen as hanged and continue at a very slow pace…. leading people to kill it : cross compiling is likely, once setup -this is a difficult task- to avoid all of these troubles)

        • Adrian Rosebrock October 20, 2018 at 7:56 am #

          Cross-compiling OpenCV for the Pi has been a royal pain in my ass. It’s not a nut I’ve been able to crack yet, unfortunately 🙁

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

      • kr September 15, 2019 at 11:57 pm #

        Hi, thanks for all the tutorials!

        I understand the reasons for a virtual env when working in python, but how does it impact this build? Does building in this venv mean it might not work in another? What if I plan to write C++ application with OpenCV and won’t use Python, should I build outside the venv? I saw another blog say don’t use a venv if you want to “make opencv installation public, to be accessible across all virtual environments.”

        My best guess is that the build process needs a specific python install, and doing it in a venv assures that. But beyond that, it should have no effect on the OpenCV built output. Does that sound right?

        One more question: if I ran cmake in the venv, but then rebooted and forgot to workon cv before running make -j4, will that cause problems? Cause I just did that. Ops!


        • Adrian Rosebrock September 19, 2019 at 10:06 am #

          If you want to use C++ that’s fine — this tutorial will give you the C++ headers installed. To answer your other question, provided you were in the “cv” virtual environment when running “cmake” it does not matter if you are in the “cv” environment when running “make”. The “cmake” command builds the configuration while “make” does the actual compile. As long as “cmake” has been run in the “cv” environment you’ll be fine.

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

  25. Phil Desrosiers October 16, 2018 at 10:02 pm #

    I’m getting an error while attempting to make. Do I need an EVEN LARGER swap file?:

    virtual memory exhausted: Cannot allocate memory

    • Adrian Rosebrock October 20, 2018 at 8:00 am #

      Unfortunately it seems like you may need a larger swap file.

  26. Ahmed Raza October 19, 2018 at 10:40 am #

    Dear Adrian
    kindly resolve my issue i am having an error “ImportError: No module named ‘picamera’ ”
    while running a python file.

    • Adrian Rosebrock October 20, 2018 at 7:29 am #

      You need to install the picamera Python library:

      $ pip install "picamera[array]"

  27. Rion Ahl October 21, 2018 at 4:31 am #

    Adrian, I have a problem, with the import cv2 as described in FAQ, but as I am a beginner, I dont really understand what to do? Could you please help?

    • Adrian Rosebrock October 22, 2018 at 8:05 am #

      Hey Rion, unfortunately without physical access to your Pi it is hard to determine where you would have made a mistake. It’s okay if you are a beginner, but you need to take the time to educate yourself on how the command line argument works, including file paths. Again, it’s impossible for me to guess what step may have tripped you up without more information so I suggest you take it slow and work through the FAQ.

  28. wenkang October 22, 2018 at 5:31 am #

    Hi Adrian,

    Can the OpenCV 3 and 4 coexist in Raspberry pi ? Or do I have to remove one if want to install the other?

    And if not, how to configure and specify the one that I want when running one python script ?


    • Adrian Rosebrock October 22, 2018 at 7:47 am #

      Both can coexist on the same machine, just create a separate Python virtual environment for your OpenCV 4 install. Other than that, no other changes are required.

  29. Jim October 24, 2018 at 7:26 pm #

    Hey Adrian, I made it most of the way through this tutorial…while compiling opencv, my Pi stops at [ 98% ] Built target opencv_perf_tracking. I expanded the swapfile size to 1024…there’s no error message, just no more progress. Should I close the terminal and start from the compiling step again? Should I make the swapfile bigger?

  30. elroy October 24, 2018 at 10:53 pm #

    Did you ever find out who stole your beer?

  31. jim421616 October 25, 2018 at 6:59 pm #

    Hi, Adrian, I posted a comment yesterday about my Pi not responding during the compile. I left it running overnight and when I came back to it, it had run out of memory. I increased the swapfile size to 2048 Mb, ran the compile again, and it works now. Thanks for your outstanding tutorials!

    • Adrian Rosebrock October 29, 2018 at 1:48 pm #

      Awesome, congratulations on getting OpenCV installed on your Pi!

  32. devashish October 26, 2018 at 8:36 pm #

    Hi adrian . i have been trying to install opencv from past 4 days. I have gone through all versions from 3.3.0 to the 4.0 . Currently in this tutorial the cmake compiled till 98% but has been like this since 1.5 hrs . This opencv thing has made be furious . Please suggest something x(.

    • Adrian Rosebrock October 29, 2018 at 1:38 pm #

      Have you tried (1) increasing your swap size and (2) compiling using just a single core? What about doing a pip install of opencv?

  33. Emilio Meza October 27, 2018 at 1:26 pm #

    Hi Adrian! I followed the steps and everything worked well on the virtual environment but, what if i want to use opencv 4 on python 3(IDLE)? there’s an easy way to do it without starting again with a different process?

    • Adrian Rosebrock October 29, 2018 at 1:32 pm #

      If you are using the same Python version for a different environment you can simply copy your bindings into the new site-packages directory for the environment. Otherwise you will need to recompile OpenCV for that specific Python version number. You may also be able to pip install opencv.

  34. Aly Rofie November 3, 2018 at 12:45 am #

    Hi Adrian, Thanks for your tutorial. But i got some problem when i’m on step 5, i can’t do “make” it says (cannot find makefile. stop), and also i can’t move into opencv directory, can you tell how to fix this?

    thank you

    • Adrian Rosebrock November 6, 2018 at 1:32 pm #

      Your “cmake” directory likely excited with an error. Go back to the “cmake” step and investigate the output to find the error. Once “cmake” executes without error then you can run “make”.

  35. David Monk November 4, 2018 at 11:51 am #

    I installed opencv-4.0.0-beta last night; I noticed the beta version was available so I downloaded the source and compiled it instead of the alpha. Seems to have compiled successfully.

    • Adrian Rosebrock November 6, 2018 at 1:24 pm #

      Awesome, congrats on getting OpenCV 4 installed on your Pi, David!

  36. Darcy November 10, 2018 at 10:57 am #

    Hey Adrian,

    Love the tutorials. You are really the main resource for opencv on raspberry pi. I’m hoping you can help me with a problem I have. I’ve gone through the tutorial 3 times now, and no matter what I do during step 5, I cannot get the interpreter, or numpy to point inside the virtual environment. What am I doing wrong?

    • Adrian Rosebrock November 13, 2018 at 5:00 pm #

      Hey Darcy, are you sure you are in the Python virtual environment when running “cmake”? Unfortunately without having physical access to your Pi I’m not sure what the issue may be. Don’t worry though, OpenCV 4 will soon be released and then you’ll be able to use pip in install opencv.

  37. balaji November 11, 2018 at 11:11 am #

    hi adrian,

    Thanks for your post,,,i follow your steps but when make -j4 command running my code gets hanged at 98% ,,i tried 3 times even it doesn’t cross 98%,,,how to resolve this issues,,,,,

    • Adrian Rosebrock November 13, 2018 at 4:53 pm #

      It sounds like your Raspberry Pi is frozen. Delete the “build” directory, re-create it, re-run “cmake”, but this time run “make” without the “-j4” option. The compile will take longer but your Pi shouldn’t lock up.

  38. Mark November 18, 2018 at 2:55 pm #

    This code does not run “as is” with the current Raspberian
    Version:November 2018
    Release date:2018-11-13
    Kernel version:4.14

    and with OpenCV 4

    The problem seemed to be two fold: It installed for Python2.7 and never could find Python 3 (per the instructions) and was missing:
    sudo apt-get install libatlas-base-dev
    sudo pip install setuptools


    • Adrian Rosebrock November 19, 2018 at 12:28 pm #

      It sounds like you created a Python 2.7 virtual environment instead of a Python 3 virtual environment. Can you check your Python virtual environment version?

  39. Austin B November 23, 2018 at 8:30 am #

    Thank you so much for this tutorial! I was able to get OpenCV 4.0.0 (official release now, no longer at pre-release) built against Python 3.6.7 on the 3 B+ in about half a day (using only “make -j2”, because I was afraid of overheating, and I was going to let it run overnight). Your instructions worked like a charm 🙂

    • Adrian Rosebrock November 25, 2018 at 9:12 am #

      Congrats on getting OpenCV 4 installed on your Pi, Austin!

  40. Chris Pinkenburg November 25, 2018 at 9:39 am #

    Hi Adrian,

    great tutorial, made installing opencv a cut and paste operation. opencv 4.0.0 is now out and I just installed it. One thing which has changed compared to the alpha version is the location of the python cv2 library. I found it in /usr/local/python/cv2/python-3.5/, not as your tutorial suggests in /usr/local/lib/python3.5/site-packages/

    • Adrian Rosebrock November 25, 2018 at 9:45 am #

      Thanks Chris — this guide was written before OpenCV 4 was officially released. OpenCV 4 was officially released last week so I’m testing out all the install instructions and updating as necessary 🙂

      • xiheng October 26, 2019 at 10:24 am #

        Great tutorial. I’m using Buster /usr/local/lib/python3.7/site-packages/cv2/python-3.7/ is the location.

  41. Tom Foltz November 27, 2018 at 11:36 am #

    When I get to this point, I’m confused on what to do. I’m a relative newbie

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

    When I enter the following: sudo nano ~/.profile
    I seem to have a problem. Maybe I don’t need sudo. I think the ~/ takes me to home, so what is the file I’m editing, “.profile” is not valid.

    • Tom Foltz November 27, 2018 at 12:21 pm #

      I’m in this section:

      Make use of virtual environments for Python development

      • Adrian Rosebrock November 30, 2018 at 9:29 am #

        No, you do not need “sudo”. Use just “nano ~/.profile” so you are editing the .profile file of the “pi” user.

  42. Ziad Alexander November 27, 2018 at 1:36 pm #

    Awesome tutorial. I am building a drone with an IR camera using openCV. But PLEASE for the love of all things holy. REMOVE the dollar signs ‘$’ from your shell lines. They are beyond annoying and serve no purpose. I still have no idea why people still do that.

    • Adrian Rosebrock November 30, 2018 at 9:26 am #

      They do serve a purpose. The “$” indicates that you are at the command line executing a command versus opened up a text file for editing, etc.

  43. Roy Georgius November 29, 2018 at 4:13 pm #

    hi, im stuck while in process make -j4 in the line 100% building CXX object module/python3/CMakeFiles/opencv_python3.dir/__/src2/cv2/cpp.o can you help me??

    • Adrian Rosebrock November 30, 2018 at 8:51 am #

      It sounds like your Raspberry Pi has hung. Stop the compile, delete your “build” directory, re-create it, and re-run “cmake” and “make”, but this time increase your swap size to 2048MB.

    • Kurt Hoffmann March 8, 2019 at 10:02 am #


      i just had the same problem during the last two days.
      Please check the effect of changing the “CONF SWAPSIZE=2048” in the dphys-swapfile using the “free -m” command before and after stopping and restarting the process.
      Does anything change?

      Forcing a swapfile of defined size (blocksize and blocks copied) might do the job:

      dd if=/dev/zero of=/var/swap.img bs=1024k count=1000
      mkswap /var/swap.img
      swapon /var/swap.img

      • Adrian Rosebrock March 13, 2019 at 4:03 pm #

        Thanks for sharing, Kurt!

  44. Chris Foley December 2, 2018 at 8:18 pm #

    I think my pi has stalled. I am at mostly 100% but the command prompt won’t come back. This is a B 3+ with swap file expanded to 2048 as specified. The compile was done with the -j4 switch. This is a BRAND NEW Pi and a brand new install. I got a bunch of warnings about clock skew and some about parameter passing being changed in GCC 7.1.

    After a lot of retries, I found that I was having some intermittant network issues. So I went bakc to a physical connection. I had some trouble figuring out why I could not switch to my cv environment locally. After editing my .bashrc file, I was up and recompiling.

    I would like to ask about the GCC 7.1 warnings. Will this be updated soon? GCC is now at 8.5?

    • Adrian Rosebrock December 4, 2018 at 10:06 am #

      I can’t comment on the GCC warnings without seeing what they were but regarding the Pi looking up, try using only a single core when compiling:

      $ make -j1

      That should, ideally prevent the Pi from locking up.

  45. Chris Foley December 3, 2018 at 7:00 am #

    Clearly I am having issues. I keep missing steps. Forgetting to change to CV and so forth. I have removed the build directory several times now and finally have a new compilation running under CV directly and not limited by my sporadic network issues. I will let this run this morning and hope that I can come home to a new compile. I still worry about “failed” errors in the build cycle. Several items were marked this way. Do I need to post those are is it normal to see a few items marked this way? Seems fishy to me but I do not know any of details of this build.

    • Adrian Rosebrock December 4, 2018 at 9:51 am #

      It’s totally normal to see the “failed” message in the “cmake” output. OpenCV has A LOT of different configurations. The “cmake” script is just checking for various configurations and reporting “failed” if it cannot find a given configuration — it’s nothing to worry about.

  46. Naveen December 3, 2018 at 11:30 pm #

    Hi Adrian,
    First of all a pretty comprehensive and well compiled tutorial.
    OpenCv Intsalltion on my pi3 B+ has been a nightmare for me. First try it got hung up , Then i had to restore my pi from backup . The Second time i tried from some other method .This time it went thru’ successful but my got listed under /home/pi and i could’t do the sym-link . I am now going to try it for the 3rd time from this link . Hopefully it works out fine . Any tips that could help me out .

    • Adrian Rosebrock December 4, 2018 at 9:41 am #

      Here are my suggestions:

      1. Increase your swap size from 1024MB to 2048MB
      2. Compile with only a single core (make -j1)

      Both of those will help the Pi from locking up.

      As for your sym-link issue that just sounds like you were in the incorrect directory when creating the sym-link. Try again but this time make sure you’re in the “site-packages” directory.

  47. Leandro Boari December 7, 2018 at 12:14 pm #

    I followed the steps and on my Raspberry Pi 3B is stopped here:

    [100%] Built target opencv_perf_stitching

    Can someone help me?

    • Adrian Rosebrock December 11, 2018 at 1:01 pm #

      It sounds like you Pi has locked up. Try increasing your swap size to 2048MB and compiling with only a single core (i.e., “make -j1”). The compile will take longer but it should prevent the Pi from locking up.

    • taufikmas March 24, 2019 at 1:47 am #

      same with me..i will try make -j1.

  48. galile December 9, 2018 at 6:20 am #

    Hi Adrian,

    When I compile opencv, it’s being 100 percent and I got no error, but the command line doesn’t come to console,its not understood it compiled or not. I mean I can’t enter new command. How can I figure out?

    • Adrian Rosebrock December 11, 2018 at 12:53 pm #

      Can you still type via your keyboard or use your mouse? Is your Pi locked up?

  49. Florin December 10, 2018 at 6:24 am #

    Hi Adrian, I have a probelm with this error

    ln: failed to create symbolic link ‘cv2/cv2’: Permission denied

    • Adrian Rosebrock December 11, 2018 at 12:45 pm #

      What directory are you when you try to create the sym-link?

  50. paul December 10, 2018 at 11:54 am #

    In “Run CMake for OpenCV 4” run those commands 1-at-a-time. THey do not work in one big copy/paste.

  51. Shashank December 10, 2018 at 11:22 pm #

    How do I install matplotlib, scikit, imutils etc after doing this procedure? Can anyone please help. And after installing this there is only 300MB left , I have uninstalled libre office , Wolfram engine etc

    • Adrian Rosebrock December 11, 2018 at 12:38 pm #

      You can use pip to install them:

      $ pip install imutils matplotlib scikit-learn

  52. Calum December 11, 2018 at 11:56 am #

    Hi Adrian,

    I am trying to install openCV without a virtual environment and for python 2.7. This is due to some additional equipment that I’m using that requires installation outside of a virtual environment and is only compatible with python 2.7. I have previously installed openCV with python 2.7 following your tutorial, but this was done in a virtual environment.
    Now that I am trying both python 2.7 and no virtual environment, I am struggling to successfully install openCV. I am able to complete the build and install steps successfully, but when I try to import cv2 i get the error ‘ImportError: No module named cv2’.
    Is there anything different I must do to install openCV in this way? How do I go about successfully importing cv2?


    • Adrian Rosebrock December 11, 2018 at 12:29 pm #

      If you can skip the Python virtual environment, that’s not a problem. The same goes for the “Troubleshooting and Frequently Asked Questions (FAQ)” section of the guide, just be sure to check the “site-packages” directory of your system install of Python 2.7. Please keep in mind that the PyImageSearch blog is now officially Python 3+ so my Python 2.7 support moving forward will be fairly limited.

  53. Geoff December 13, 2018 at 10:59 pm #

    Thanks for the tutorial. I was able to install OpenCV4 on my RaspPi 3. I tried -j4 which got mo to 100%…then it seemed to hand. I started over with -j1, left it for 2 hrs, and it finished.

    Now that that works, I am trying to import this into Python 3, but am having trouble. When I enter “import cv2 as cv2” into Python 3, I get this error:

    “ImportError: No module named ‘cv2’

    Am I missing something?

    • Adrian Rosebrock December 18, 2018 at 9:29 am #

      Make sure you refer to the “Troubleshooting and Frequently Asked Questions (FAQ)” section where I discuss most of the reasons why that may happen.

    • Hayat July 17, 2019 at 2:06 am #

      hi i think that i solve this issue by using python3 instead of just python before you import cv2
      i got it to work that way. hope this help you out

  54. LeninGF December 15, 2018 at 10:45 pm #

    Hello everyone …. Thanks to author for guiding in installation. It worked. However I am wondering if conda could be used, since I am kind of more comfortable with that.

    I have a question. I followed the instructions but when I start up the Raspberry Pi I cant enable the virtual env cv from command line. I always have to run the command source ~/.profiles and then I can do workon cv….. Is there a way to fix this? Did I do something wrong?

    • Adrian Rosebrock December 18, 2018 at 9:09 am #

      You could use the conda environment if you wanted but it gets tricky to correctly supply the conda Python paths if you’ve never done it before. I only recommend doing it if you have good experience debugging Python paths.

      As far as your question goes, the source ~/.profile command only needs to be executed once per terminal session. That is normal.

  55. Montel Hudson December 18, 2018 at 2:40 am #

    When I open a new terminal to check if If my cv is working and I enter workon I get.bash: workon: command not found, why is that happening I followed everything step by step

    • Adrian Rosebrock December 18, 2018 at 8:47 am #

      It sounds like you have not installed virtualenv and virtualenvwrapper properly OR you have not updated your .profile correctly. Double-check those steps.

  56. Jaydip Bari December 20, 2018 at 2:41 am #

    Hey there ,
    I have successfully installed opencv4. But now the problem is that I want to start my python script on raspberry pi on startup and it seems that I cannot enable virtual environment at startup. Please guide me how should I enable virtual environment and start my script. Please reply me with my email id.

    • Adrian Rosebrock December 20, 2018 at 5:10 am #

      Make sure you refer to the “Troubleshooting and Frequently Asked Questions (FAQ)” section where I include detailed instructions on how to debug not being able to find your Python virtual environment. My guess is you’re forgetting to use the source ~/.profile command before workon cv

  57. djef December 21, 2018 at 5:20 am #

    hello , i am using raspberry pi b+ and i had succefully install open cv like this blog but when i tried the sample below and in the scp pi@192168 1 1 athey aask me a password plzzzzzzzzzzzz any help

    • Adrian Rosebrock December 27, 2018 at 11:01 am #

      The password to your Raspberry Pi is likely the default password, “raspberry”

  58. Tjaart December 21, 2018 at 11:27 pm #

    Hi there

    I am a complete noob… but have managed to install Opencv4 and Tensorflow in two different virtual machines. Thanks for a great tutorial on CV4 install.

    How ever I cant import tensorflow when working in the Opencv 4 environment, so I am trying to follow your tutorial but installing it outside a virtual environment.
    The cmake errors out and I am a noob so the error file makes no sense to me.

    1 Could you please consider a short vid or tutorial to setup opencv 4 outside virtual environment.

    I would love to enter your “The PyImageSearch Gurus course” but I will get lost in the first lesson.
    2 Have you ever considered a classroom setup where the enrolled people can ask Q? as you go?

    • Adrian Rosebrock December 27, 2018 at 10:56 am #

      Do you already have OpenCV 4 installed into your Python virtual environment? If so, you should be able to install TensorFlow via:

      As far as the PyImageSearch Gurus course goes, I have designed the course to help you study computer vision even if you are totally new to computer vision. I also have provided pre-configured development environments you can use (no need to configure your system). You just download the virtual machine, install it with a few clicks, and you’re ready to go! I would suggest you give the course a try, I think it will really help you.

  59. Hanno December 22, 2018 at 1:14 am #

    This was the only tutorial that worked flawlessly to install and run CV 4. Thanks Adrian.

    • Adrian Rosebrock December 27, 2018 at 10:54 am #

      Thanks Hanno! And congratulations on getting OpenCV 4 installed on your Pi!

  60. Saami December 25, 2018 at 1:29 pm #

    Hey i came across a problem when i was making an ocr program using your method with tesseract and open cv it says no module named pytesseract i am using a raspberry pi 3

    • Adrian Rosebrock December 27, 2018 at 10:24 am #

      You need to install the pytesseract lbirary:

      $ pip install pytesseract

  61. Pandora December 30, 2018 at 4:57 pm #

    Is it really okay to ignore the mismatch between the compiletime and runtime versions along with the runtime errors?

    • Adrian Rosebrock January 2, 2019 at 9:20 am #

      What runtime errors are you referring to?

  62. Ethan December 31, 2018 at 12:17 pm #

    Hi Adrian!

    Thanks for the walk through. I have a question concerning doing this on a Raspberry Pi Zero W. I followed through all of your instructions and when it came time to try and import cv2 in the python environment, it threw an error. “FATAL ERROR: This OpenCV build doesn’t support current CPU/HW configuration”. Under that it says “Required baseline features: NEON – NOT AVAILABLE”. I did some research and found that the raspberry pi zero doesn’t support NEON? Can you confirm this? Also, what would be my steps to backtrack and fix this. Do I need to go back and run cmake with the neon flag turned off? What should I delete or do before I do this so I don’t have two sets of opencv libraries? Thanks for all of your help!

  63. Steffen January 7, 2019 at 8:01 am #

    Hey Adrian,

    thank you very much for everything! Just a short question: Can the folders opencv and opencv_contrib be deleted after successful installation? Or they still necessary for opencv to work?

    • Adrian Rosebrock January 8, 2019 at 6:51 am #

      Once OpenCV has been successfully installed you can delete the “opencv” and “opencv_contrib” directories.

  64. Brad January 10, 2019 at 9:49 pm #

    It looked like I successfully completed each step, and on step 7 (test) it still says version 3.4.2

    Is this somehow related to the virtual environment from the older OpenCV? Each time I enter workon cv I need to enter source ~/.profile, or I get a bash error.

    • Adrian Rosebrock January 11, 2019 at 9:30 am #

      Did you create a new Python virtual environment for your OpenCV 4 install? If so, you definitely need to.

      • Brad January 11, 2019 at 10:56 am #

        Hi, thanks for the quick response, I did the virtual environment as per step 4 above. I’ve been over the tutorial on virtual environments, but can I redo step 4 without re-installing OpenCV 4?

        • Adrian Rosebrock January 11, 2019 at 1:24 pm #

          Yes, you can do it over, just make sure your sym-link is correct. I get the impression that you may have installed a previous version of OpenCV on your Pi before you followed this tutorial though.

          • Brad January 12, 2019 at 10:57 am #

            Thanks, that did it. I just repeated steps 4 and 7, and named the new virtual environment cv4.

            Yes, I have opencv 3.4.1, 3.4.2, and now 4 installed.

          • Adrian Rosebrock January 16, 2019 at 10:12 am #

            Awesome, I’m glad that worked!

  65. Peter January 11, 2019 at 4:19 pm #

    I would just like to say that this is one of the most useful and comprehensive ‘How-to’ articles I have ever followed. Not only did each step work, but each step both taught me and explained things along the way.

    A brilliant, well thought out practical article.

    You should be proud of this.

    Thank you for all your hard work.


    • Adrian Rosebrock January 16, 2019 at 10:19 am #

      Thank you Peter, I really appreciate your kind words. Your comment really made my day 🙂

  66. Dalil Maadour January 12, 2019 at 8:44 am #

    Hi, when I do the “make -j4” command, the raspberry freeze at 100% of the loading.. help me pleaase

    • Adrian Rosebrock January 16, 2019 at 10:12 am #

      See the sentence in the post that starts with “If you have compile errors or your Raspberry Pi hangs/freezes you can try without the -j4 switch which can eliminate race conditions.”

  67. Dalil Maadour January 13, 2019 at 1:24 pm #

    Hi Adrian, I’ve been installed and compiled opencv, but when I want to do “import cv2”, the IDE answers me an error. What is the problem ? 😮

    • Adrian Rosebrock January 16, 2019 at 10:04 am #

      I don’t know which IDE you are using, but if it’s anything like PyCharm you likely need to set the Python project interpreter to point to the Python virtual environment. See this tutorial on instructions to do exactly that.

  68. rohit January 15, 2019 at 12:34 pm #

    in opencv4 sift is not working
    error is
    File “”, line 5, in
    AttributeError: module ‘cv2’ has no attribute ‘SIFT’

    • Adrian Rosebrock January 16, 2019 at 9:38 am #

      That’s not how you access SIFT in OpenCV 3 and OpenCV 4. See this tutorial.

      You should be using:

      sift = cv2.xfeatures2d.SIFT_create()

  69. Caleb January 15, 2019 at 2:43 pm #

    I’m having trouble with step #5. Everything seems to compile just fine in my virtual environment, but when I check the output, I can’t find anything indicating that the compiler is pointing to python 3 and numpy. Any suggestions?

    • Adrian Rosebrock January 16, 2019 at 9:36 am #

      Make sure you use the “workon” command to access your Python virtual environment first. It sounds like you may have missed that step.

  70. Shaun January 18, 2019 at 9:21 am #

    Nice work as always.

    I ran out of swap while building and the Pi 3b hung. I discovered a way to temporarily increase the swap file on the fly (no reboot) which allowed me to save the build. I’ll be using this in the future rather than changing the default swap space with /etc/dphys-swapfile in the future.

    # ==================
    # Add 3Gb of extra swap
    # ==================
    sudo dd if=/dev/zero of=/var/swap2 bs=3072M count=1024
    sudo mkswap /var/swap2
    sudo chmod 0644 /var/swap2
    sudo swapon /var/swap2

    # Check it’s been added
    sudo swapon –show

    # ==================
    # Removing the swap file
    # ==================
    sudo swapoff /var/swap2

    # Check it’s been removed – wait if it hasn’t
    sudo swapon –show

    # Remove the swap file
    sudo rm -f /var/swap2

    • Shaun Price January 30, 2019 at 9:22 pm #

      Correction. The first line should have been:
      sudo dd if=/dev/zero of=/var/swap2 bs=1024 count=3M

  71. spinoza January 18, 2019 at 1:11 pm #

    Excuse me, there will be some way to optimize opencv and install without graphics, I am currently using it for object recognition with audio output and I do not require graphics. thanks greetings.

    • Adrian Rosebrock January 22, 2019 at 9:38 am #

      Are you referring to a headless install of your Pi and OpenCV?

  72. Stephen Gloor January 20, 2019 at 6:57 am #

    Hi Adrian – I just wanted to install it without the virtual environment as this machine is just going to run scripts not really develop them.

    I had to link up the with this:

    cd /usr/local/lib/python3.5/dist-packages/
    ln -s /usr/local/python/cv2/python-3.5/

    It then worked OK

  73. Ben January 23, 2019 at 7:13 am #

    Hi Adrian

    Firstly, thanks for the tutorial updates; everything’s much clearer and more comprehensive now. I have two questions regarding virtual environments building on things that you have referenced:

    1. Several of the blogs that you suggest reading re virtual environments imply that python’s inbuilt (v3.3+) virtual environment tool “venv” is better than “virtualenv.” Any chance your instructions could contain some notes on why you use the older “virtualenv” tool and what differs if using “venv” (alternate cmake screenshots would be ideal)

    2. In a couple of your replies above, you briefly mention that you use symlinks to make opencv available in multiple virtual environments with the same python version without reinstalling a new copy of opencv on each one. Any chance you could give more detailed instructions on how to do this? I’d really like to know how to make environments share site packages of my choosing to save space and am struggling to find instructions online.

    Thanks in advance!

    • Adrian Rosebrock January 25, 2019 at 7:27 am #

      1. Whether you use virtualenv or venv is a matter of preference. Have you tried using either? What has your personal preference been?

      2. If you’re having trouble understanding sym-links I would suggest reading the “man ln” documentation first. Here is another simple tutorial you can refer to. Try creating your own sym-links to files on your desktop, in your documents directory, etc. I get the impression that you may be new to Unix systems — that’s totally okay but make sure you walk before you run first. Grasp making basic sym-links first before you start trying to share files across multiple site-packages directories.

  74. Olen January 26, 2019 at 9:35 am #

    Hi Adrian,

    My Pi hung up during the compilation at this point : [100%] Built target opencv_perf_superres

    I have increased the SWAP to 2G, I have deleted and created again the build folder twice and started the process allover again but it always hangs at 99% or 100%

    What else can I try?
    If I compile with a single core it is certain that it will complete the compilation?


    • Adrian Rosebrock January 29, 2019 at 6:53 am #

      Yes, try compiling with a single core — that should resolve the issue.

      • Virgil January 31, 2019 at 9:32 pm #

        Do i hv to delete the build folder, or i just continue with the make command ?

        • Adrian Rosebrock February 1, 2019 at 6:39 am #

          I recommend always deleting your “build” directory if you compiled with more than one core and your Pi locked up. It’s hard to say what state the compile was left in. Re-create the “build” directory then re-run “cmake” and “make”

      • Krishan June 22, 2019 at 8:32 am #

        Yes, try compiling with a single core But I stuck at 100%

        • Adrian Rosebrock June 26, 2019 at 1:39 pm #

          If you’re still running into issues you might want to utilize a pip install of OpenCV. I also offer a pre-configured Raspbian .img file with OpenCV pre-installed inside Practical Python and OpenCV. That .img file will get you up and running with OpenCV on the RPi in a matter of minutes.

  75. KH January 27, 2019 at 6:45 pm #

    Hi Adrian, after successfully completing step 7 and the sanity check for the version number (it all worked till that point), I tried to follow your tutorial “Accessing RPi wth OpenCV” on the capture of single image I was getting the import cv2 error.

    I am using a Win 10 laptop and doing SSH into a headless Pi 3 Model B loaded with Stretch Lite, Pixel Desktop and Thonny Python IDE .

    This is what I did to partially solve the problem.

    After the carrying out the following steps:
    1) typing the follow commands at SSH command line:
    cd /usr/local/lib/python3.5/dist-packages/
    ln -s /usr/local/python/cv2/python-3.5/


    2) amending the follower in the interpreter parameters in Thonny from the default option “The same interpreter which runs Thonny…” to “alternative python 3 interpreter or virtual environment”

    and amending the default path from “/usr/bin/python3” to


    and then I was able to run your tutorials on capturing a single image and also accessing the webcam videostream.

    I mentioned the problem is solved partially only because I can only run the python programs in the Pixel GUI desktop environment , not the SSH command line.

    I had already followed the instructions left by another forum reader to install Xming server on windows and also the ssh -X command and also enabled the X11forwarding in the X11 config file. But I still get error messages when trying to run the python files in SSH command line.
    The error messages are “connect localhost port 6000: Connection refused

    (Image:4413): Gtk-WARNING **: cannot open display: localhost:11.0 ”
    How can I solve this ?

    Secondly, the partial solution I used seems to suggestion the interpreter path in Thonny was not pointing to the ./virtualenv… path of the interpreter.
    How can I solve this problem if I wish to follow your steps in working with a virtual environment ?

    Apologies for the long mail, I am seeking help as this is meant for a school project.
    Thank you.

    • Adrian Rosebrock January 29, 2019 at 6:44 am #

      You mentioned you are using a headless Pi and that you installed X11 on your Windows system. Did you install X11 on your Pi though? You’ll need X11 installed on the Pi as well.

      As far as Thonny goes I don’t use that IDE and I’m not familiar with it. If it’s like other Python IDEs you can set the Python project interpreter to point to your virtual environment. You may need to do your own research there.

      • KH January 29, 2019 at 1:15 pm #

        Hi Adrian, how do I go about installing X11 on the Pi?

        Secondly, is there any Python IDE that you can recommend where it is easy to use and install on the Pi in the SSH command line environment? I had to resort to using Thonny based on what I could google. So far, my difficulty with Thonny is I can’t seem to amend the path of the interpreter. That seems to be what is driving the “missing cv2 ” error messages when running the python code.

        I started out with the Stretch Lite and installed the Pixel desktop with very bare software hence there was no IDLE software in it and I am trying to avoid reinstalling the Stretch Desktop image if possible.

        • Adrian Rosebrock February 1, 2019 at 7:25 am #

          1. I would suggest you do some research on how to install X11 on the Pi. There are a number of different packages that you may need to install and I cannot answer that directly for you. Take the time do some research on how to install X11 on the Pi.

          2. I would suggest using Sublime Text 2 on the Pi. Sublime Text is a nice editor. You may also want to look into using PyCharm from your laptop/desktop and have the files automatically upload to the Pi.

    • Stephen July 23, 2019 at 8:01 pm #

      The big problem with setting up anything inside a Virtual Environment on Raspberry Pi is that it you would need to set up the IDE to work in a Virtual Environment. I’ve looked at each of the IDEs that come with the Pi and found Thonny to be the only one that allowed me to set up the Virtual Environment and run OpenCV per directions from here.

      1. Start Thonny -> Options -> Interpreter
      2. Change to: “Alternative Python 3 Interpreter or Virtual Environment
      3. Set Link by using Locate Another Python Executable
      4. Click on top of Window where the directory input should be and just start typing and the folder user input bar should appear.
      5. Go to : /home/pi/.virtualenvs/

      Select file:

      And now the Virtual Environment should be added to your Thonny IDE.

  76. Sam January 29, 2019 at 12:08 am #

    Hello Adrian,

    Thanks a lot for the detailed procedure. I got the CV installed finally by making use of the make command without passing the j flag.

    • Adrian Rosebrock January 29, 2019 at 6:34 am #

      Congrats on getting OpenCV installed on your Pi!

  77. Virgil January 31, 2019 at 9:26 pm #

    Hey guys, i think i need some help, i try to install the opencv like 3 or 4 times, but always end up with an error or freeze, thou i already try the make and make -j4 command…
    please help

    • Adrian Rosebrock February 1, 2019 at 6:39 am #

      Have you increased your swap size as well?

  78. Hamza February 6, 2019 at 10:36 am #

    Hello everyone, i tried to install opencv4 2 times but again it blocks in 100%, i can still move the mouse or write something with the keyboard. I don’t know what to do, i increased my swap and, tried first time with make -j4 , and second time with only make, but still doesnt work.
    i have an rpi 3 B+ and a sd card 16go .

    • Hamza February 6, 2019 at 11:02 am #

      It worked ! , i had to wait longer,

      now, when i open a new terminal and tape ; workon cv

      it does not work till i tape the command before : source ~/.profile

      can anyone explain that to me please ?

      • Adrian Rosebrock February 7, 2019 at 7:03 am #

        What is the exact error you are getting? Without knowing the error I cannot diagnose or provide any suggestions.

  79. Jordan February 6, 2019 at 5:12 pm #

    Will this tutorial simply not work on a Raspberry Pi 2 Model B, or will it just take a long time?

    • Adrian Rosebrock February 7, 2019 at 6:58 am #

      It will take a long time but provided you have Raspbian installed, yes, it should work.

  80. Ian February 7, 2019 at 8:23 pm #

    I have succesfully installed open cv 4 in my rasp pi 3 via putty.
    But the problem is that i cannot acces the program when i connect my pi directly to my monitor.
    I hope you can help me.

    • Adrian Rosebrock February 14, 2019 at 2:59 pm #

      It sounds like you may be forgetting to use the “workon” command to access your Python virtual environment before executing the script.

  81. Hariharan February 10, 2019 at 8:03 pm #

    Hey Adrian,

    The compilation always seems to be stuck at “Scanning dependencies of target opencv_python 2” and then produces an error even if I increase the swap and use “make -j1”.

    Please help me resolve this issue.

    • Adrian Rosebrock February 14, 2019 at 1:43 pm #

      That’s definitely strange behavior. What is your exact error?

  82. Hariharan Gopalakrishnan February 10, 2019 at 9:47 pm #

    Hi Adrian,

    I was successfully able to install OpenCV4 but when I try to import cv2 …”I got import module: no such module name “cv2”.

    1) “workon cv” works.
    2) There is cv2 symlink directory in site-packages. I
    3) There is cv2 directory in /usr/local/python .
    4) I tried the last step indicated in the FAQ section for this question.

    Still, cv2 can’t be imported please help me.

    • Adrian Rosebrock February 14, 2019 at 1:42 pm #

      Are you in your Python virtual environment via the “workon” command before trying to import the “cv2” bindings?

      • Hariharan Gopalakrishnan February 15, 2019 at 6:09 pm #

        Yes. I was

        • Adrian Rosebrock February 20, 2019 at 12:49 pm #

          Can you import OpenCV outside of your Python virtual environment? It sounds like at some point your Python versions got mixed up or your sym-link was placed in the incorrect location. Unfortunately, without access to your Pi it’s extremely hard to diagnose. I would suggest you try again with a fresh install of Raspbian.

  83. John February 11, 2019 at 10:26 am #

    hi adrian
    i am trying to make the use_dropbox true
    but when i get in the json file by using the terminal, i dont know how to change it
    can u pls tell me how to enable the use_dropbox


    • Adrian Rosebrock February 14, 2019 at 1:31 pm #

      You can use your favorite text editor to edit the JSON file. That could be your terminal (vim, emacs, nano) or a text editor. Open up the JSON file and then change the setting.

  84. Volker von Einem February 11, 2019 at 1:42 pm #

    Thank you very much for the great instructions!
    I installed OpenCV 4.0.1 but didn’t do dist upgrade before – worked like a charm with only a few tweaks.

    • Adrian Rosebrock February 14, 2019 at 1:29 pm #

      Fantastic, congrats on getting OpenCV 4 installed on your Raspberry Pi!

  85. anabelle February 15, 2019 at 3:07 am #

    i cant install opencv and opencv contrib. please help.

    • anabelle February 15, 2019 at 3:20 am #

      it says “wget” not recognised ….im using windows 10.

      • Adrian Rosebrock February 15, 2019 at 6:12 am #

        This tutorial is for installing OpenCV 4 on a Raspberry Pi, not Windows 10. Make sure you are executing the commands on the Pi.

    • vamc February 23, 2019 at 4:50 am #

      connect to internet then download from github later unzip it

  86. anastasia February 16, 2019 at 5:52 am #

    hi Adrian,
    While compiling open cv, some of the dependencies reached 100% at last , but when i go up, some didnt reach 100%….is it normal?

    • Adrian Rosebrock February 20, 2019 at 12:45 pm #

      Was OpenCV able to successfully compile? Or did your Pi freeze up and get “stuck”?

      • anastasia February 27, 2019 at 12:54 am #

        no its ok now..thanks 🙂

  87. Ivan Surya H February 16, 2019 at 1:10 pm #

    hi, I just want to help with error for importing cv2module, actualy for me, the location of is not at the Adrian’s tutorial where it said “ln -s /usr/local/python/cv2/python-3.5/”

    so I deleted the old and then found new location of

    then the command become like this:
    ln -s /usr/local/lib/python3.5/site-packages/cv2/python-3.5/

    Thanks Adrian for the tutorial.

    and it worked like a charm for me.

    • Andy April 18, 2019 at 5:15 pm #

      Can confirm, worked for me as well. Thanks Ivan!

    • Boipelo Zuma July 8, 2019 at 7:53 am #

      You saved my life! Can reaffirm, this works. Thanks Ivan!

  88. Mark February 17, 2019 at 4:30 pm #

    Hi Adrian. Just worked my way through this tutorial, no problems. Worked a treat on my Pi 3 B+. Great work. Thanks

    • Adrian Rosebrock February 20, 2019 at 12:36 pm #

      Fantastic, congrats on getting OpenCV installed on your Pi!

  89. wpimuhammadali February 21, 2019 at 4:41 am #

    dear Adrian, i already install the Opencv as your instruction, and is working after installed, moreover at the moment i restart my raspberry pi, and write “import cv” is gives error no such command.
    could you please tell me what is wrong ?
    thank you in advance

    • Adrian Rosebrock February 22, 2019 at 6:35 am #

      The name of the OpenCV bindings is actually “cv2”, not “cv”. It also sounds like you didn’t launch a Python shell before trying to import.

  90. Miles Archer February 21, 2019 at 6:42 pm #

    Thanks for the great write up. Took more than 24 hours to compile on a raspi Zero. But it did finish. With hindsight, -j4 is probably not a good choice for a single core processor. 😉

    • Miles Archer February 21, 2019 at 8:26 pm #

      Whoops. Yeah, it compiled, but it doesn’t run. The processor is missing NEON support. Looking at other options…

      • Adrian Rosebrock February 22, 2019 at 6:21 am #

        Compiling OpenCV on a Raspberry Pi Zero is a royal pain. I don’t recommend it. The Pi Zero is extremely underpowered and isn’t a good solution for computer vision. I would honestly try to use a Pi 3 if at all possible, the performance gains will be significant and it will be far easier to install.

  91. Werner Boecker February 23, 2019 at 2:25 am #

    Hi Adrian, thanks for this great tutorial. But I have one problem. I have done all steps but if I try to import cv2 I will get an error. If I check my installed modules using “pip freeze” it shows me only numpy. There is an file in the site-packages directory of my virtualenv but no cv2 directory. The virtualenv works fine and I got the (cv) prompt after the workon cv command. What went wrong? Thanks for your help and your great work!

    • Adrian Rosebrock February 27, 2019 at 6:19 am #

      Unless you installed OpenCV via “pip” you will not see OpenCV listed in the output of “pip freeze”. Double-check that your sym-link is a valid one, it’s likely that the sym-link is pointing to a file that doesn’t exist.

      • Justin Gruber March 7, 2019 at 8:30 pm #

        I am having a similar issue as the original post. I had few questions regarding the symbolic link as well. I understand where the file that is first stated in the line “/usr/local/python/cv2/python-3.5/” is located but what is the file location of the “” that the symbolic link is being created with? Is that the file that is located in the virtual environment?

        • Adrian Rosebrock March 8, 2019 at 5:22 am #

          The location of where the sym-link should reside is the “site-packages” directory of your Python virtual environment:


  92. Ravindra Patil February 25, 2019 at 3:13 am #

    Adrian sir, can i use the raspberry pi with this opencv4 and python3 virtual installation for practical projects and how can i access this isolated environment please give detailed information.

    • Adrian Rosebrock February 27, 2019 at 5:59 am #

      Yes, you can use this method with multiple OpenCV versions installed. Just create a new Python virtual environment for each OpenCV version you want installed. Compile and then sym-link in your bindings to the “site-packages” directory of the Python virtual environment.

  93. Ravindra Patil February 25, 2019 at 3:50 am #

    i want to run my opencv python code in python 3 idle and dont want virtual enviornment so what changes should i does in the above procedure please answer sir

    • Adrian Rosebrock February 27, 2019 at 5:58 am #

      Python IDLE does not respect Python virtual environments. I would suggest you use Jupyter Notebooks instead.

  94. Javier February 25, 2019 at 5:20 pm #

    Hi Adrian,
    I found a raspberry with OpenCV 4.0.0 alpha that i should have installed last year.
    And now i want to build the face recognition that you made. Do you sugest me to continue with this “alpha version”?? or should i update it to the latest.
    If i have to update it, should a update/upgrade command be enough? or i have to installed from the beginning.

    Thanks a lot

    • Adrian Rosebrock February 27, 2019 at 5:50 am #

      You won’t be able to update/upgrade, you need to download the source code of OpenCV 4 that you would like to utilize then compile it.

  95. Amrin February 27, 2019 at 1:37 am #

    Hi, I’ve been trying to compile opencv on rpi zero w…and it is stuck at 100% Building CXX object modules/python2/CMakeFiles/opencv_python2.dir/__/src2/cv2.cpp.o for about a day now ?

    So I’ve tried remake it using make (single threading) but still stuck there…swap file is 2048mb…the pi is not freezing, it is still responsive

    • Adrian Rosebrock February 27, 2019 at 5:29 am #

      Compiling and installing OpenCV on a Pi Zero W can be a huge pain — my only suggestion here would be to increase your swap size again.

  96. Arbaz Pathan March 9, 2019 at 1:20 pm #

    Hi Adrian,
    I completely followed the steps, but while compiling the opencv it got stuck after completing 100%. From where should I resume

    • Adrian Rosebrock March 13, 2019 at 3:52 pm #

      Try re-compiling but this time:

      1. Increase your swap size to 2048MB
      2. Compile with a single core

      The compile will take longer but shouldn’t freeze.

  97. gülce March 10, 2019 at 7:39 am #

    Hi Adrian,
    I had an error too in the j4 command. my raspberry freezed and i closed the command window. Then when I restarted raspberry It worked too slowly. Why is that? any suggestions?

    • gülce March 10, 2019 at 9:44 am #

      Hi again,
      After some errors I finally install open cv. Thanks to you!
      Meanwhile, pi is slower than before opencv installation. Is there any thing to do for this?

      • Adrian Rosebrock March 13, 2019 at 3:43 pm #

        Congrats on getting OpenCV installed on your Pi, nice job!

  98. sweetsouce March 11, 2019 at 8:37 am #

    Is it possible to install opencv_contrib after installing opencv? I am running rasbian stretch on 8GB sd card and need to preserve memory as much as possible, so I was thinking of installing opencv first then delete contents of build and then building opencv_contrib. Can you help?

    • Adrian Rosebrock March 13, 2019 at 3:37 pm #

      No, you will need to re-compile and re-install OpenCV, unfortunately.

  99. kumar March 18, 2019 at 11:47 am #

    I want to install Open CV 4.0 without a virtual environment in raspberry-pi. may I know what setups to flow?.

  100. Keyur Modi March 25, 2019 at 7:22 am #

    Thanks you so much. I successfully installed OpenCV4.

    • Adrian Rosebrock March 27, 2019 at 8:53 am #

      Congrats on getting OpenCV 4 installed on your Pi! Nice job.

  101. Kartik Kharbanda March 27, 2019 at 7:41 pm #

    Hi Adrian I followed your steps exactly the way they are but when i run the make -j4 command the raspberry pi freezes and I know you said to just type in make if it does that but it also freezes when i type in make by itself. it gets to a 100% and freezes and I can’t get past that. Any way of fixing the issue?

    • Adrian Rosebrock April 2, 2019 at 6:38 am #

      Try using “make -j1” instead to compile with just a single core.

  102. jmr March 31, 2019 at 10:13 am #

    Hi Adrian,

    thanks so much for your installation instuctions. I did both the Mac and the Raspi installation and they worked right away, so I could run the 2 sample projects.
    From other experiences I made, I can estimate and value the amount of time you saved me.

    Looking forward to learning how to implement my own project.

    • Adrian Rosebrock April 2, 2019 at 5:58 am #

      Congrats on getting OpenCV 4 installed on your Pi, nice job!

  103. Karl April 1, 2019 at 10:39 am #

    Hi Adrian, what a great tutorial.

    Like others, I am hung on the make step at about 92% compete. The machine is totally unresponsive.

    I’m going to try increasing the swap file size to 2048 like others have done. My question is: do I need to do anything special to clean up after the failed make before trying it again?

    Many thanks for all that you do.

    • Adrian Rosebrock April 2, 2019 at 5:51 am #

      You can try to restart the compile but this time use just “make -j1” to compile with only a single core.

  104. Peter April 3, 2019 at 2:06 pm #

    If I will install OpenCV according to your tutorial will I be able to write code in C++ with openCV libraries and then compile it or I have to use python?

    • Adrian Rosebrock April 4, 2019 at 1:15 pm #

      You will be able to use both C++ and Python.

  105. Andy April 15, 2019 at 12:56 pm #

    Hi Adrian, im following your tutorial, but when I run the CMake, the “OPENCV_ENABLE_NONFREE=ON” flag doesnt seem to work, as it does not enable the non free aspects (wich I really need for my current project).

    Any advice?

  106. Bob H April 18, 2019 at 10:06 am #

    I installed per your instructions last night and everything seemed to work but when I ran the check in the tutorial I got the following error:

    AttributeError: module ‘cv2’ has no attribute ‘_version_’

    I thought it might be my linking but I double checked the paths so it should be correct. Any ideas on what to do next?

    (Also have not done the symbolic link thing before. Can a link be removed if its wrong?)

    • Adrian Rosebrock April 25, 2019 at 9:37 am #

      This is almost definitely a sym-link issue of some sort. Can you import the “cv2” library correctly from your “build/lib” directory?

  107. Wassim racheh April 26, 2019 at 2:05 pm #

    Hello, i’m trying to install opencv4 on my raspberry pi 3 b+, i was following all the steps,
    But the build stucks at 100%,
    [100%] Built target opencv _perf_stitching
    I incresed the swapfile to 2048 and i tryed make-j1, make and make -j4 but always the same prob it stucks at 100%
    Ps: i stil can use my pi still responsive.
    I need help please it’s for my final project and thanks.

    • Cai June 3, 2019 at 5:31 am #

      just wait, it does not stuck, it just Needs a little bit time.

  108. Andrwe C April 30, 2019 at 8:42 am #

    I just had the same issue, the paths are a bit different than the examples shown above. Just verify your path and your symbolic link will work.

    • diana cuevas May 9, 2019 at 9:32 pm #

      I have the same problem as wassim, what do you mean by the paths are different?

  109. Ronald Mourant May 5, 2019 at 7:09 am #

    When I tried to install numpy with the statement
    $ pip install numpy
    I got a code 1 error.

    Then I tried:
    $ pip install ‘numpy==1.15’
    and it worked!

    • Roberto Alini August 3, 2019 at 7:24 pm #

      Thanks Ronald for the suggestion. It worked also for me but the command is without thick ‘ otherwise it gives me error

      $ pip install numpy==1.15

  110. Aj May 19, 2019 at 12:39 am #

    Hi Adrian ,

    I am done with the entire steps as specified above with no errors but yet import error is thrown when i import cv2 , can someone help me out ?

    • Adrian Rosebrock May 23, 2019 at 9:55 am #

      What steps from the “Troubleshooting and Frequently Asked Questions (FAQ)” section have you tried?

  111. Ambarish May 28, 2019 at 8:09 am #

    Is there anyway to install opencv 4 for jetson nano? I have tried it but I end with error and not compiling. So can I use the same method for even jetson nano?

    • Adrian Rosebrock May 30, 2019 at 9:14 am #

      See the comments of this post.

  112. Cai May 31, 2019 at 5:34 am #

    Hi Adrian. Thanks a lot for that amazing guide! But I got a Problem with GUI/GTK installation. “Unable to fetch some archives, maybe run apt-get update or try with –fix-missing?” Even I tried update it still dosen’t work. Then I just went on with the other part, and the other went well. Now I can import opencv, and see the vision. But when I do other like preview something relevant with GUI/GTK, then I get BUG. Do you know how can I fix it? Thanks:)

    • Adrian Rosebrock June 6, 2019 at 8:42 am #

      It sounds like it may be an issue with your apt-get definitions. Try doing:

      $ sudo apt-get update

      If that doesn’t work try flashing a fresh version of Raspbian.

  113. DickM June 2, 2019 at 11:28 am #

    Hi Adrian

    I was so proud of myself – although 99% of the kudos should go to your great, clear tutorial – as I appeared to successful install OpenCV 4.1.0 on my Pi3B+. Not only that but I installed it as a Docker image! It didn’t even take too long: certainly not the 3 or 4 hours your earlier tutorials were suggesting.

    HOWEVER when I popped the SD card out of the 3B+ and tried it in a ZeroW things looked fine until I tried to “import CV2” in python3 when I got “Illegal instruction (core dumped)”.

    Do I need to compile separately for the 3B+ and for the ZeroW?

    • Adrian Rosebrock June 6, 2019 at 8:09 am #

      The Zero W is a bear to work with. You need to compile OpenCV separately on the Zero W, unfortunately.

  114. Cai June 3, 2019 at 5:28 am #

    Hi Adrian, thanks for sharing. I got a question, I counld not download the GUI and GTK paket, even though I updated the apt-get. It still did not work, any ideas? Thanks a lot!

  115. jose motta June 4, 2019 at 10:20 am #

    Hi Adrian, congrats for the great job done!

    In case we build a docker container starting from debian/stretch, the project wouldn´t need to create a virtual environment. In this case, the global install would save some space in memory, isn’t?

    Do you already have a docker file containing the instructions from this post? Then it would be simpler to just “docker run -it”.

    • Adrian Rosebrock June 6, 2019 at 6:52 am #

      Docker would introduce more overhead than just a Python virtual environment. Your Docker instance itself would also require more storage than just the Python virtual environment. I would not go that route unless you wanted to keep your system packages themselves separate from your host system.

  116. Hiep Le June 15, 2019 at 3:17 am #

    Thank you very much. Using your guide, I’ve have successfully installed OpenCV 4.1.0 on my Raspberry Pi 3+.

    There a small fix, however. The path to is not correct for me, so I have to change it to:

    ln -s /usr/local/lib/python3.5/site-packages/cv2/python-3.5/

    Perhaps you should mention it in your guide. It may help other people

  117. Darren June 26, 2019 at 11:39 pm #

    If you are trying to build this on the ‘buster’ version which uses Python 3.7 then you lin command has changed quite a bit.

    cd ~/.virtualenvs/cv/lib/python3.7/site-packages

    ln -s /usr/local/lib/python3.7/site-packages/cv2/python-3.7/

    • Adrian Rosebrock July 4, 2019 at 10:58 am #

      Thanks for sharing Darren!

    • Sahil August 24, 2019 at 11:14 am #

      I have been trying to install it from the last week now. (well this field is new to me.)
      everyone i recommend to follow this tutorial for RASPBIAN BUSTER in RPI4B model. and please do the above commands modifications for SYM-LINK suggested by DARREN.

      Thanks a lot, Adrian and Darren

  118. diogo July 9, 2019 at 11:21 am #

    Hi, great job for this tutorial!!

    For those who want to install opencv for c++ development, what would be the changes in this tutorial? Is it necessary to do the steps 4 and 6?


  119. Denis I. July 10, 2019 at 7:33 am #

    Hi Adrian! Grat article.

    I have a question. I was able to successfully install OpenCV 4.1 on my Paspberry Pi 3b+. However as per you advice I installed it in a virtual enviornment. However, I am trying to use a FaceRecognition module for MagicMirror ( that runs outside of that enviornment and therefore cv2 module cannot be found.

    Is there a way for me to “take out” the cv2 module outside of the virtual enviornment?


    • Adrian Rosebrock July 10, 2019 at 9:31 am #

      Yes, provided that your Python virtual environment version matches your system Python version, just move the “” bindings into the “site-packages” directory of your system Python install.

  120. Shawn July 10, 2019 at 5:02 pm #

    Hello! This is a really helpful guide! I’m stuck on the make -j4 line. it seems to get to 100% and then it is stuck on line
    [100%] Built target opencv_python2
    [100%] Building CXX object modules/python3/CMakeFiles/opencv_python3.dir/__/src2/cv2.cpp.o
    does this normally take a long time?
    Thank you!

    • Adrian Rosebrock July 25, 2019 at 10:18 am #

      Yes, it can take a bit of time.

  121. Letty B. July 12, 2019 at 12:36 pm #

    Hi Adrian! Great tutorial!

    I have a question, I try to install opencv on an orange pi rk3399, with armbian aarch64. I was able to get to step 6, to link opencv into my python virtual environment without any errors, but when I try to test opencv I get this:

    File “”, line 1, in
    ImportError: No module named ‘cv2’

    I already check your FAQ section and…

    1. I have my virtual environment is active.
    2. I have check the contents of the site-packages directory in the virtual environment and there is a cv2 sym-link directory in the site-packages directory and it’s properly sym-linked.
    3. Also I check in /usr/local/python/ and Ihave a cv2 directory there.
    4. But I thing this is the weird part when I try to use the last resort by going to build/lib directory of my opencv build, there isn’t a cv2 directory there, even though all the steps run without any errors.

    Do you have any ideas of what could be happening?

    Letty B.
    Thanks in advance

    • Adrian Rosebrock July 25, 2019 at 10:10 am #

      Thanks Letty; however, I have not tested these instructions with the Orange Pi. My suggestion is to check your “build/lib” directory (it may be in “build/lib/python3” as well).

  122. B.Karthikeyan July 14, 2019 at 1:05 am #

    Hi Adrian,

    Initially I tried with make -j4. At 100% of build completion, the Pi locked up. So terminated the build process. Tried again with make -j1 and everything went well.

    Now OpenCv is installed in my Pi.

    • Adrian Rosebrock July 25, 2019 at 10:06 am #

      Congrats on getting OpenCV installed on your RPi!

  123. srujan July 15, 2019 at 11:05 am #

    Hi Adrian,
    I followed the same instructions on Raspberry Pi 4B on a freshly installed Raspbian Buster headless (July 10th release). Everything worked perfectly. the make -j4 took me 44 minutes. I am wondering if there are any new updated video/image libraries specific to Rpi 4 which might increase the overall performance of Pi.


    • doni September 16, 2019 at 2:57 am #

      hi. i also tried Rpi4 with this step but stuck with import cv2 in step 7, trying to copy from folder python2.7 to python3.7 but acces denied also with mv, chmod command also acces denied. its look like you already try the Rpi4 with for image processing task how its performance like the FPS. thank you

  124. Stephen July 22, 2019 at 7:47 pm #

    Is there a version of these instructions for installing without virtualenvironment or at least a more detailed instruction set on how to run a .py file in any of the native IDEs on the Pi with a virtual environment since “workon cv” doesn’t activate inside an IDE.

    • Adrian Rosebrock July 25, 2019 at 9:32 am #

      It will work inside an IDE, you just need to change your Project Interpreter first. Make sure you refer to this tutorial.

  125. Venkat July 23, 2019 at 11:22 am #

    Hi , Thanks for the Info , i followed your instructions and commands step by step and successfully installed the Opencv and confirmed by checking the cv2 version and shows 4.0.
    but when I opened the new terminal and tried for $ workon cv it say’s
    ‘ Bash: workon :command not found’ . any suggestion on this ?


    • Adrian Rosebrock July 25, 2019 at 9:30 am #

      It sounds like you may not have ran the “source ~/.profile” command.

  126. Col h July 24, 2019 at 7:21 pm #

    Thanks for this tutorial, just a note that this worked just fine on a raspberry pi 4 (2G) and with no heatsink it compiled in around an hour, I thought it had hung at the 99% mark but it just needs to be left alone for 10-15 minutes or something.

  127. AndK July 27, 2019 at 12:28 pm #

    Adrian, thanks for the great tutorial.

    I been trying it a couple of times. One time it went right through (I saved an image 🙂 )but all the other times it keeps stalling at a very specific point of your described process. Hope you or someone can be helpful!

    I avoid step #4 since the rpi 3b is a single purpose machine with 32gb sd-card with noobs (I also remove wolfram and libre).
    I only perform last step of step #4: install numpy but the response is it is already satisfied.

    I follow step #5, step-by-step, and the last instruction I make is: make -j4
    It starts fine, and progress up to 100% happens ok fast, but then every time it stalls at:
    [100%] Built target opencv_perf_stitching

    The rpi does not freeze, I can run top in a new terminal and see something is happening, but even after several hours no progress on step #5. I can do other functions on the rpi, but it happens slowly. CPU is allocated to step#5, but no progress?

    Hope someone has any constructive ideas?


    I have left it running over night but no progress. It reaches this stall point rather fast.

  128. Mark August 1, 2019 at 6:04 pm #

    Great article Adrian.

    I installed it with

    sudo apt-get install libopencv-dev python3-opencv

    Seems to work on raspi 3

    • Adrian Rosebrock August 7, 2019 at 12:37 pm #

      I really don’t recommend doing that. Using “apt-get” to manage Python packages often installs older, outdated versions. It also installs them into the system “site-packages” which can become really messy and is not a good practice for Python development.

      Either way, congrats on getting OpenCV installed!

  129. Uwe Kleis August 3, 2019 at 6:27 am #

    Hello Adrian
    First of all Sorry because my english is not very good and I use Google Translator
    I installed opencv after your description and everything worked
    after a reboot I can not use the command Workon cv anymore the message “bash workon command not found” appears
    Can you help me here?

    • Adrian Rosebrock August 7, 2019 at 12:32 pm #

      Make sure you run “source ~/.profile” first.

  130. electron1979 August 6, 2019 at 12:06 am #

    I seem to have installed oCV 4.1.1 😉

    • Adrian Rosebrock August 7, 2019 at 12:22 pm #

      Congrats on getting OpenCV installed!

  131. Antony Smith August 13, 2019 at 7:43 am #

    Hi guys,

    I’ve just installed a fresh version of the latest raspbian – BUSTER and having major issues installing OpenCV 4.1.1 AND OpenCV 4.0.0??

    I’ve successfully installed 4.0.0. on Jessie without any issues before, but it seems to fail consistently on BUSTER??

    I’ve tried all combinations of SWAPFILE (1024, 2048) with make -j(1, 2, 4) and never make it past 48%.

    Considering rolling back to Jessie, unless you guys have suggestions?

    • Adrian Rosebrock August 16, 2019 at 5:41 am #

      I’ll have a dedicated tutorial for Raspbian Buster and OpenCV 4, stay tuned!

      • Chris Carroll August 16, 2019 at 9:52 pm #

        Would LOVE to see that. Been struggling to get 4.1.1 compiled on Buster (pi 4) for several days and still haven’t figured it out. Your expertise would be much appreciated.

        • Adrian Rosebrock September 5, 2019 at 11:04 am #

          It’s coming later this month (September 2019)! Just putting the instructions through a few final tests.

      • Marie August 19, 2019 at 7:19 am #

        Any news on when you will publish it? I have been trying for days, getting it to work on Raspbian Buster, but I’m always getting an error, when I’m importing cv2. (ModuleNotFoundError: No module named ‘cv2’)
        Thanks in Advance and all the content!

        • Adrian Rosebrock September 5, 2019 at 11:00 am #

          Definitely sometime in September. Stay tuned!

    • Starsmer August 24, 2019 at 7:44 am #

      I’m glad I’m not alone on this one. managed to make it to 51% after a few attempts at 2048 and -j4, but still no prize there either. anyway, looking forward to the new tuit!

  132. jonathan August 15, 2019 at 3:18 am #

    hi Adrien,
    first, im in love with your blog.
    second: I couldn’t compile with but only with . does it mean the compilation will be slower? or the application at run time?
    thank you. (for this and for everything that’s on pyimagesearch

  133. BBC_Basic August 20, 2019 at 4:57 pm #

    Will this tutorial work on Raspberry Pi 4 with 4GB ram?

  134. BBC_Basic August 20, 2019 at 5:00 pm #

    Sorry just seen that this will work

  135. Frieda Rhema August 27, 2019 at 4:48 am #

    Hello Adrian,
    Thanks for this awesome tutorial.
    I have an issue at the level of the command make -j4, When i use this command, my pi crashed. After reinstalling it, i used just make but it seems not to work because my pi always freezes when i get to a hundred percent. I have been on it for three days now. Your help would highly be appreciated.
    I am using a raspberry pi3 model B+ with a 32GB memory card.

    • Adrian Rosebrock September 5, 2019 at 10:46 am #

      Try using only a single core via “make -j1”. The compile will take longer but it should work.

  136. RajPan August 28, 2019 at 7:18 am #

    Thank you Adrian. Great step-by-step guide. Anxiously waiting for your tutorial for Raspbian Buster and OpenCV 4,

    • Adrian Rosebrock September 5, 2019 at 10:41 am #

      It will be live later this month 🙂

  137. Sunil V September 5, 2019 at 9:25 am #

    I was able to install OpenCV4.1.0 on Pi4-4G with Raspbian Buster. Wondering if I can copy binaries the next time from the SD card without having to do cmake again. Is that possible ? If yes, what binaries do I need to copy over?

  138. Daniel Krotov September 12, 2019 at 11:30 pm #

    So I tried the pre-compiled image on my newest RPi4B Raspbian Buster and it didn’t work (Now seeing the comment about you working on something)…regardless, I decided to take a stab at following your steps here and I just had to thank you for putting this all together. It went perfectly….time consuming of course, but absolutely perfect! I can’t wait to start playin around with this hardware….for now it is time to get some shut eye.

    • Adrian Rosebrock September 19, 2019 at 10:15 am #

      Congrats on getting OpenCV installed on your Pi, Daniel!

      And just to clarify, the Raspberry Pi .img file that was released yesterday fully supports the RPi 4, Raspbian Buster, and OpenCV 4.

    • Nazarii October 14, 2019 at 5:28 pm #

      for raspbian buster (no stretch) link OpenCV 4 into your Python 3 (last step):

      cd /usr/local/lib/python3.7/dist-packages/cv2
      sudo ln -s /usr/local/python/cv2/python-3.7/
      (without virtualenv)

  139. jyotish October 22, 2019 at 4:14 pm #

    workon cv is also some time not work after restart

    • Adrian Rosebrock October 25, 2019 at 10:19 am #

      Make sure you source ~/.profile first.

  140. Eli November 19, 2019 at 2:14 pm #

    Hi, dont see my previous question yet, but found an answer to the “select timeout resource unavailable” issue when trying to do video capture with USB webcam.

    I instead did video capture (in the script) and passed it a url instead of a device number.

    First, compile/install mjpg-streamer, get that working.

    then your url would be something like this:

    • Adrian Rosebrock November 21, 2019 at 9:07 am #

      Thanks for sharing, Eli!

  141. Deepak November 30, 2019 at 1:09 am #

    Hi Adrian, I want to install Opencv 3.3 in Raspberry 4. But I’m getting error in make. But Opencv 4.1.0 will install smoothly without error. Is there any possibility for installing Opencv 3.3 in Raspberry 4?

  142. Larry Springsteen November 30, 2019 at 4:16 pm #

    At step 4 I hit a dead end. It says – To finish the install of these tools, we need to update our ~/.profile !!!

    What where and HOW?


    • Adrian Rosebrock December 5, 2019 at 10:34 am #

      Hey Larry — updating your ~/.profile file is discussed in the tutorial. Did you run into an error when trying to update it?

  143. Andrew December 7, 2019 at 8:12 pm #

    Hello Adrian,

    On the step where I compile the cv, i keep getting error at 85%. The error i keep encounter is Makefile:163: all. any ideas? Ive updated the swap to 2048 and used make & make -j1 instead of the original make -j4. Still no improvements.

    Could you help me out?

  144. George December 8, 2019 at 11:50 am #

    Hi, I’ve problem to install: my system compile with cmake only with 2.7 version. Could you tell me how I can delete 2.7 or tell to cmake to use 3.7 ? Thank you.

  145. sweeney January 2, 2020 at 4:58 pm #

    Hey Adrian,

    I just found this on a website and it seemed to work.

    Thanks for your tutorial. Very helpful.

  146. cedric euchie January 5, 2020 at 8:36 am #

    is possible to install opencv4 in Raspberry 3b+?

    • Adrian Rosebrock January 16, 2020 at 10:54 am #

      Yes, simply follow this tutorial.

  147. cedric euchie January 5, 2020 at 12:07 pm #

    hallo Adrian inside raspbian and opencv preinstall this finds also already dlib,and imutils?if such is the case I can already start with facial recognition?

    • Adrian Rosebrock January 16, 2020 at 10:54 am #

      Are you referring to my pre-configured Raspbian .img file?

      If so, yes, it comes with OpenCV, dlib, imutils, etc. pre-installed, enabling you to jump right into your project.

  148. Yehonatan Peleg January 14, 2020 at 5:42 pm #

    Great help, thx a lot. have a good week

    • Adrian Rosebrock January 16, 2020 at 10:29 am #

      Thanks, I’m glad you enjoyed the tutorial!

Before you leave a comment...

Hey, Adrian here, author of the PyImageSearch blog. I'd love to hear from you, but before you submit a comment, please follow these guidelines:

  1. If you have a question, read the comments first. You should also search this page (i.e., ctrl + f) for keywords related to your question. It's likely that I have already addressed your question in the comments.
  2. If you are copying and pasting code/terminal output, please don't. Reviewing another programmers’ code is a very time consuming and tedious task, and due to the volume of emails and contact requests I receive, I simply cannot do it.
  3. Be respectful of the space. I put a lot of my own personal time into creating these free weekly tutorials. On average, each tutorial takes me 15-20 hours to put together. I love offering these guides to you and I take pride in the content I create. Therefore, I will not approve comments that include large code blocks/terminal output as it destroys the formatting of the page. Kindly be respectful of this space.
  4. Be patient. I receive 200+ comments and emails per day. Due to spam, and my desire to personally answer as many questions as I can, I hand moderate all new comments (typically once per week). I try to answer as many questions as I can, but I'm only one person. Please don't be offended if I cannot get to your question
  5. Do you need priority support? Consider purchasing one of my books and courses. I place customer questions and emails in a separate, special priority queue and answer them first. If you are a customer of mine you will receive a guaranteed response from me. If there's any time left over, I focus on the community at large and attempt to answer as many of those questions as I possibly can.

Thank you for keeping these guidelines in mind before submitting your comment.

Leave a Reply