In this tutorial, you will learn how to pip install OpenCV on Ubuntu, macOS, and the Raspberry Pi.
In previous OpenCV install tutorials I have recommended compiling from source; however, in the past year it has become possible to install OpenCV via pip, Python’s very own package manager.
While installing from source will give you the greatest control over your OpenCV configuration, it’s also the hardest and the most time-consuming.
Though not directly requiring a dataset, using a variety of images after installing OpenCV using pip can help verify the installation and understand the basics of the library.
Roboflow has free tools for each stage of the computer vision pipeline that will streamline your workflows and supercharge your productivity.
Sign up or Log in to your Roboflow account to access state of the art dataset libaries and revolutionize your computer vision pipeline.
You can start by choosing your own datasets or using our PyimageSearch’s assorted library of useful datasets.
Bring data in any of 40+ formats to Roboflow, train using any state-of-the-art model architectures, deploy across multiple platforms (API, NVIDIA, browser, iOS, etc), and connect to applications or 3rd party tools.
If you’re looking for the fastest possible way to install OpenCV on your system, you want to use pip to install OpenCV (but there are a few things that may trip you up along the way, so make sure you read the rest of this guide).
2019-11-21 Update: An update has been issued to this blog post due to compatibility issues with OpenCV on the Raspberry Pi 4 running BusterOS using this pip install method. Be sure to find the updates via ctrl + f
as you search for “2019-11-21 Update”.
To learn how to pip install OpenCV on your system, just keep reading.
Looking for the source code to this post?
Jump Right To The Downloads Sectionpip install OpenCV
In the remainder of this tutorial, I’ll briefly describe the OpenCV packages you can install via pip, Python’s package manager.
From there, I’ll demonstrate how to pip install OpenCV on Ubuntu, macOS, and the Raspberry Pi.
Finally, I’ll review some common problems you may encounter when using pip to install OpenCV.
I’d like to point out an important caveat to this OpenCV installation method before we begin.
The PyPi/PiWheels hosted versions of OpenCV that we’re discussing today do not include “non-free” algorithms such as SIFT, SURF, and other patented algorithms. This is a great method to install OpenCV if you need a quick environment in which you won’t need to run programs containing the non-free algorithms — if that’s not the case, you’ll need to complete a full compile of OpenCV.
The two pip OpenCV packages: opencv-python
and opencv-contrib-python
Before we get started I want to remind you that the methods I’m coming here today are unofficial pre-built OpenCV packages that can be installed via pip — they are not official OpenCV packages released by OpenCV.org.
Just because they are not official packages doesn’t mean you should feel uncomfortable using them, but it’s important for you to understand that they are not endorsed and supported directly by the official OpenCV.org team.
All that said — there are four OpenCV packages that are pip-installable on the PyPI repository:
- opencv-python: This repository contains just the main modules of the OpenCV library. If you’re a PyImageSearch reader you do not want to install this package.
- opencv-contrib-python: The opencv-contrib-python repository contains both the main modules along with the contrib modules — this is the library I recommend you install as it includes all OpenCV functionality.
- opencv-python-headless: Same as opencv-python but no GUI functionality. Useful for headless systems.
- opencv-contrib-python-headless: Same as opencv-contrib-python but no GUI functionality. Useful for headless systems.
Again, in the vast majority of situations you will want to install opencv-contrib-python
on your system.
You DO NOT want to install both opencv-python
and opencv-contrib-python
— pick ONE of them.
How to pip install OpenCV on Ubuntu
You have two options to install OpenCV on Ubuntu with pip:
- Install into your system
site-packages
- Install into a virtual environment’s
site-packages
(preferred)
First, install some OpenCV dependencies on Ubuntu
We need to refresh/upgrade the pre-installed packages/libraries with the apt-get package manager:
$ sudo apt-get update $ sudo apt-get upgrade
Followed by installing two required packages:
$ sudo apt-get install python3-dev $ sudo apt-get install libgl1-mesa-glx
Next, install pip
If you don’t have pip, you’ll need to obtain it first:
$ wget https://bootstrap.pypa.io/get-pip.py $ sudo python3 get-pip.py
Option A: Install OpenCV to your Ubuntu system with pip
I wouldn’t recommend this method unless you have a particular use case where you don’t want isolated, independent Python environments.
Let’s pip install opencv-contrib-python on our system:
$ sudo pip install opencv-contrib-python
In a matter of seconds, OpenCV is ready to go in your system’s site-packages!
Option B: Install OpenCV on Ubuntu into a virtual environment with pip
There are huge benefits to Python virtual environments.
The main benefit is that you can develop multiple projects on your system with isolated packages (many with version dependencies) without having to muddy the waters of your system. You’re also free to add and remove virtual environments as you go.
Put simply: Python virtual environments are a best practice for Python development. Chances are, you should jump on the bandwagon.
My tools of choice are virtualenv
and virtualenvwrapper
but you could choose an alternative such as venv or Anaconda (conda for short).
Here’s how to install virtualenv
and virtualenvwrapper
, both of which will live in your system site-packages
and manage each project’s virtual environment site-packages:
$ pip install virtualenv virtualenvwrapper
Before we can continue, you first need to add some lines to your ~/.bashrc
profile. Open the file using nano
, vim
, or emacs
and append these lines to the end:
# virtualenv and virtualenvwrapper export WORKON_HOME=$HOME/.local/bin/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 export VIRTUALENVWRAPPER_VIRTUALENV=$HOME/.local/bin/virtualenv source $HOME/.local/bin/virtualenvwrapper.sh
Save the file. Then “source it” in your terminal:
$ source ~/.bashrc
You’ll see some terminal output which sets up virtualenvwrapper. You now have access to new terminal commands:
- Create an environment with
mkvirtualenv
. - Activate an environment (or switch to a different one) with
workon
. - Deactivate an environment with
deactivate
. - Remove an environment with
rmvirtualenv
. - Be sure to read the docs!
Let’s create a Python 3 virtual environment for OpenCV called cv:
$ mkvirtualenv cv -p python3
And now with a magic wand (pip), you can pip install OpenCV in a matter of seconds into your new environment:
$ pip install opencv-contrib-python
How to pip install OpenCV on macOS
MacOS is similar to Ubuntu for pip-installing OpenCV.
Again, you have two options to install OpenCV on macOS with pip:
- Install into your system
site-packages
- Install into a virtual environment’s
site-packages
(preferred)
Install pip
If you don’t have pip, you’ll need to obtain it first:
$ wget https://bootstrap.pypa.io/get-pip.py $ sudo python3 get-pip.py
Option A: Install OpenCV to your macOS system with pip
Don’t do this.
Why? I actually recommend that you go to the Option B and use a virtual environment.
Okay, well if you insist on installing on your macOS system, then it’s just as easy as pip installing OpenCV via:
$ sudo pip install opencv-contrib-python
In a matter of seconds, OpenCV is ready to go in your system’s site-packages.
Option B: Install OpenCV on macOS into a virtual environment with pip
Just like managing packages is a breeze with pip….
…managing projects and their dependencies is a breeze with virtual environments.
You should use Python virtual environments if you’re serious about computer vision development (or any development for that matter).
I don’t care what system you use (be it virtualenv
, venv
, or conda
/Anaconda), just learn to use one and stick with it.
Here’s how to install virtualenv and virtualenvwrapper, both of which will live in your system site-packages and manage each project’s virtual environment site-packages:
$ pip install virtualenv virtualenvwrapper
From there, you need to add the following lines to your ~/.bash_profile
(notice that for macOS the file name is .bash_profile
and for Ubuntu it is .bashrc
.
Open the file using nano
, vim
, or emacs
(nano
comes on most systems):
$ nano ~/.bash_profile
…and append these lines to the end:
# virtualenv and virtualenvwrapper export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3 source /usr/local/bin/virtualenvwrapper.sh
Save the file — if you are using nano
the keyboard shortcuts are listed at the bottom of the window.
Then “source it” in your terminal:
$ source ~/.bash_profile
You’ll see a few lines of terminal output indicating that virtualenvwrapper is set up. You now have access to new terminal commands:
mkvirtualenv
: Make a new virtual environment.workon
: Activate/switch to a virtual environment. Remember, you can have as many environments as you’d like.deactivate
: Jumps out of a virtual environment and you’ll be working with your system.rmvirtualenv
: Deletes a virtual environment.- Be sure to read the docs!
Let’s create a Python 3 virtual environment for OpenCV called cv:
$ mkvirtualenv cv -p python3
And now, using pip, and with a blink of an eye, you can pip install OpenCV on macOS in a matter of seconds into your new environment:
$ pip install opencv-contrib-python
How to pip install OpenCV on Raspberry Pi
Earlier in this post I mentioned that one of the downsides of installing OpenCV is that you don’t have any control over the compile itself — the binaries are prebuilt for you, which while nice, also means you can’t include any additional optimizations.
For the Raspberry Pi, we’re in luck.
Dave Jones (creator of the picamera
Python module) and Ben Nuttall of the Raspberry Pi community-run piwheels.org, a Python package repository providing ARM wheels (i.e., pre-compiled binaries packages) for the Raspberry Pi.
Using PiWheels you’ll be able to pip install OpenCV in a matter of seconds (the same is true for other Python libraries that can take a long time to compile, including NumPy, SciPy, scikit-learn, etc.).
So how do you instruct the pip command to use PiWheels?
The short answer is “Nothing!”
If you’re using Raspbian Stretch you’ll be pleased to know that the pip command will check PiWheels for a pre-compiled binary before it checks PyPI, enabling your Pi to save a bunch of CPU cycles (and you a bunch of install time).
Furthermore, when Ben and Dave put together the OpenCV binary for PiWheels they asked me which instructions they should use — I recommended my optimized OpenCV install for the Raspberry Pi — which is exactly the instructions they followed!
If you end up using pip to install OpenCV on your Raspberry Pi, rest assured, you’re using the optimized version.
Let’s get started learning how to pip install OpenCV on our Raspberry Pi.
Install prerequisites on your Raspberry Pi
The Raspberry Pi requires that you install a few system packages before you get started:
$ sudo apt-get install libhdf5-dev libhdf5-serial-dev libhdf5-103 $ sudo apt-get install libqtgui4 libqtwebkit4 libqt4-test python3-pyqt5 $ sudo apt-get install libatlas-base-dev $ sudo apt-get install libjasper-dev
Install pip on your Raspberry Pi
The Python package manager, “pip”, can be obtained via wget:
$ wget https://bootstrap.pypa.io/get-pip.py $ sudo python3 get-pip.py
Now you have two options:
- Install OpenCV to your global Python
site-packages
on your Raspberry Pi - Install OpenCV into a virtual environment on your Raspberry Pi
Option A: Install OpenCV to your Raspberry Pi system with pip
I wouldn’t recommend this option if you want to be able to use different versions of OpenCV in isolated environments.
But a lot of people deploy their Raspberry Pis for only one purpose/project and don’t need virtual environments.
That being said, it is quite a mess to clean up if you change your mind later and want to use virtual environments, so I’d recommend skipping this option and following Option B.
To pip install OpenCV on your Raspberry Pi system, be sure to use sudo like this:
$ sudo pip install opencv-contrib-python==4.1.0.25
2019-11-21 Update: Readers have reported that some versions of OpenCV 4 as installed via pip do not work properly on the Raspberry Pi. You may encounter an "undefined symbol: __atomic_fetch_add8"
for libatomic
error when you import cv2
from Python if you do not use the specific version of OpenCV mentioned in the code block above.
In a matter of seconds, OpenCV is ready to go in your Raspberry Pi’s site-packages along with any other packages you may have installed.
Option B: Install OpenCV into a virtual environment with pip on your Raspberry Pi
Virtual environments are definitely the way to go if your Raspberry Pi has multiple purposes (or if you’re like me and test code compatibility among various software versions for blog posts all the time ?).
Here’s how to install virtualenv and virtualenvwrapper, the tools I use to get it done:
$ pip install virtualenv virtualenvwrapper
Then you need to add the following lines to your ~/.bashrc
. Open the file using nano
, vim
, or emacs
and append these lines to the end:
# virtualenv and virtualenvwrapper export WORKON_HOME=$HOME/.local/bin/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 export VIRTUALENVWRAPPER_VIRTUALENV=$HOME/.local/bin/virtualenv source $HOME/.local/bin/virtualenvwrapper.sh
Save the file. Then “source it” in your terminal:
$ source ~/.bashrc
Terminal output will be printed indicating that virtualenvwrapper is ready. Be sure to inspect it for errors.
You now have access to new terminal commands:
- Create an environment with
mkvirtualenv
. - Activate an environment (or switch to a different one) with
workon
. - Deactivate an environment with
deactivate
. - Remove an environment with
rmvirtualenv
. - Be sure to read the docs!
To create a Python 3 virtual environment which will house OpenCV and other packages you install, simply use mkvirtualenv and the command below:
$ mkvirtualenv cv -p python3
Now you have a virtual environment named cv
. You can activate it any time via:
$ workon cv
And now with a flip of the wrist, you can pip install OpenCV into cv
:
$ pip install opencv-contrib-python==4.1.0.25
2019-11-21 Update: Readers have reported that some versions of OpenCV 4 as installed via pip do not work properly on the Raspberry Pi. You may encounter an "undefined symbol: __atomic_fetch_add8"
for libatomic
error when you import cv2
from Python if you do not use the specific version of OpenCV mentioned in the code block above.
That’s all there is to it with PiWheels!
I bet you’re using the PiCamera as your imaging sensor. You can install the Python module using the following command (just take note of the quotes):
$ pip install "picamera[array]"
Testing our pip install of OpenCV
Did you know that OpenCV’s 3.3+ has a DNN module which can run Deep Learning models?
You might be surprised, but your version of OpenCV can do this out of the box now, with little to no additional software.
We’re going to perform object detection in video with a MobileNet Single Shot Detector.
Here’s what you need to install first (assuming a cv
virtual environment):
$ workon cv $ pip install imutils $ pip install "picamera[array]" # if you're using a Raspberry Pi
Now double check that you have all software ready by opening a Python shell:
$ workon cv $ python Python 3.6.3 (default, Oct 4 2017, 06:09:15) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import cv2 >>> cv2.__version__ '4.0.1' >>> import imutils >>>
The Raspberry Pi will show a different version of Python 3, which is expected.
Now it’s time to download the code.
Be sure to use the “Downloads” section of this blog post to download the source code + pre-trained MobileNet SSD neural network.
From there, execute the following command:
$ python real_time_object_detection.py \ --prototxt MobileNetSSD_deploy.prototxt.txt \ --model MobileNetSSD_deploy.caffemodel [INFO] loading model... [INFO] starting video stream... [INFO] elapsed time: 55.07 [INFO] approx. FPS: 6.54
I’m using a Macbook Pro. A framerate of 6 FPS is pretty good using a CPU on a laptop.
Raspberry Pis are resourced constrained, therefore we can leverage a few tricks to create the illusion of higher FPS. If you’re on the Raspberry Pi, execute the following command:
$ python pi_object_detection.py \ --prototxt MobileNetSSD_deploy.prototxt.txt \ --model MobileNetSSD_deploy.caffemodel [INFO] loading model... [INFO] starting process... [INFO] starting video stream... [INFO] elapsed time: 48.55 [INFO] approx. FPS: 27.83
Here I’ve created the illusion of fast 27 FPS on the Raspberry Pi while the neural network in the background is only capable of processing 0.9 FPS.
How is this possible?
Threading and queues.
It’s a little bit advanced, but if you read the original blog post (for the Raspberry Pi), you’ll understand the process. Plus, you’ll be able to impress your friends and family.
What to look out for when using pip to install OpenCV
To start, not all Python distributions will have a version of OpenCV that is pip-installable.
Newer versions of Python and newer operating systems (and not to mention, older versions which have reached their end of life) may not have a version of OpenCV ready to go in the PyPI repository as the open source community has not had a chance to release such a version yet.
In those situations you can either:
- Wait until the binaries for your combination of Python and OS are uploaded.
- Or what my recommendation would be — compile from source (Ubuntu, macOS, RPi).
Secondly, some readers, including Anaconda users, have reported problems using GUI functions such as cv2.imshow
and cv2.waitKey
.
In these scenarios, OpenCV will error out saying that it was not compiled with GTK or QT support.
Simply put:
- You’ll be able to use all other OpenCV functions but you won’t be able to use any of the GUI functions, in particular, the ones in the highgui module.
- The solution here is to compile from source (Ubuntu, macOS, RPi).
Third, I know readers have reported issues when executing import cv2
in their terminals, Jupyter Notebooks, or Python shells — this isn’t an issue with the pip install of OpenCV.
In most, but not all, situations, the error is not related to your actual install of OpenCV.
Instead, it’s more likely a problem with your understanding of some combination of:
- The commands that were executed and how to utilize them properly.
- Thinking that a command executed correctly but instead resulted in an error.
- Failing to access your Python virtual environment (if you are using one).
You’ll want to double-check your commands, repeat the steps, and examine your output closely before reporting an issue importing the cv2
bindings.
Finally, the version of OpenCV that will get installed via pip does not include “non-free” algorithms such as SIFT, SURF, and other patented algorithms. If you don’t need to use patented algorithms, then you’re golden. Otherwise, I recommend that you compile OpenCV from source via one of my installation tutorials for your system.
What's next? We recommend PyImageSearch University.
86 total classes • 115+ hours of on-demand code walkthrough videos • Last updated: October 2024
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled
I strongly believe that if you had the right teacher you could master computer vision and deep learning.
Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?
That’s not the case.
All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.
If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.
Inside PyImageSearch University you'll find:
- ✓ 86 courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 86 Certificates of Completion
- ✓ 115+ hours of on-demand video
- ✓ Brand new courses released regularly, ensuring you can keep up with state-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Access to centralized code repos for all 540+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Summary
In today’s tutorial, you learned how to pip install OpenCV on your operating system.
Specifically, we covered how to install OpenCV via pip on Ubuntu, macOS, and Raspberry Pi.
While installing OpenCV via pip may be the easiest method to get you started, keep in mind that you may run into other issues.
If you find yourself running into errors or problems using your pip install of OpenCV, be sure to refer to the “What to look out for when using pip to install OpenCV” section of this blog post.
I hope you enjoyed today’s tutorial!
To be notified when future blog posts are published here on the PyImageSearch blog, be sure to enter your email address in the form below.
Download the Source Code and FREE 17-page Resource Guide
Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!