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.
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? I recommend PyImageSearch University.
30+ total classes • 39h 44m video • Last updated: 12/2021
★★★★★ 4.84 (128 Ratings) • 3,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:
- ✓ 30+ courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 30+ Certificates of Completion
- ✓ 39h 44m on-demand video
- ✓ Brand new courses released every month, 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 500+ 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!
David Hoffman
This method with pip has come a long way — it is an easy way to get started with OpenCV and lowers the barrier to entry for many folks. Thanks for sharing Adrian!
kaisar khatak
Will “pip install opencv-contrib-python==3.4.3” leverage the GPU or is it CPU only functionality??? If we want OpenCV to use the GPU, must we compile OpenCV from source???
Ubuntu 16 (AWS P2 instance)
Thanks!
Adrian Rosebrock
It will likely only use your CPU. For any type of optimizations or GPU support I would highly encourage you to compile from source.
Raj Pandey
And Yes I am using a USB camera not a PIcamera so will it work? Do I need to Install Picamera?
Dany
Thank you Adrian. It’s possible install two version of OpenCv in two separated enviroment?
David Hoffman
Hi Dany. Yes. Try this:
Max Lee
I noticed these extra packages show up in the repository a few days ago and thought I was just mistaken… I’m so glad to see that they are real, and that they are from you.
Thank you so much, congrats on your marriage, and take care!
wally
This is awesome news! About your honeymoon and openCV!
Hopefully openCV 4 will be built soon after its release.
I expect I will try it soon on a PiZero-W with Movidius.
I know you recommended a minimal openCV installed for NCS but I have been using the NCS with OpenCV 3.4.2 compiled on Ubuntu 16.04 by building the NCS sdk with the old repo version of openCV, and then creating a python virtual environment and compiling ocv 3.4.2. I then got the ncs api to work by simply copying the mvnc python module to my virtual environment.
It seems to work as I’ve pulled together several of your tutorials into a single python script that will use the ncs if one is plugged in and fall back to using the cpu only dnn module if no ncs devices are found or its running on Windows (limited testing so far). I can select using multiple onvif netcameras (my preferred solution now since round robin sampling of multiple cameras is trivial), the picamera module, or a USB webcam.
For performance, pretty much need the ncs on a Pi, on an i7 cpu dnn module is significantly faster. On an i3 (windows) the Pi with ncs is about the same as the cpu only dnn. My speed conclusions could be in error if the pre-compiled windows openCV is using gpu acceleration with the opencv-contrib-python version.
David Hoffman
Hi Wally, thanks for sharing about your experience with Movidius. As far as the Pi Zero W, I haven’t tried to pip install OpenCV on it yet — I think it will work, but I’m not sure. On the Pi Zero W, I’ve only had luck with Raspbian Jesse. I couldn’t compile OpenCV on Stretch despite multiple attempts. I haven’t used Onif Netcameras — thanks for sharing about it.
Jerome
Once upon a time, pip 🙂
great news
thanks for sharing Adrian !
fred
Will save me much time to compile the source code, thank you Adrian.
Bojan Matovski
Sorry if I missed it, but I didn’t saw any comments as to what’s the difference between opencv-python and opencv-contrib-python.
I’m looking forward to this pip based install, but I’m just having a feeling that something will not work as intended. Maybe when it will be officially accepted by opencv.org I will change my mind, but up till then I will just stick to the old fashioned way (unless I need to do it fast on some machine).
I mean, I’ve done it so many times and on so many machines (mostly thanks to you and your tutorials of course) that I really feel very comfortable installing it from scratch.
Anyway, all the best and cheers for the new tutorial!
Abhishek Thanki
Hi Bojan,
The difference is that opencv-contrib-python includes modules in the contrib repository as well. The contrib repository contains algorithms such as SIFT, SURF, and others. In the past, these implementations were included in the default installation; however, they were moved beginning with OpenCV 3+.
Modules that are actively being developed and/or modules that are patented (not free for commercial/industry use) are included in the contrib module. For example, SIFT and SURF fall into this category.
I can assure you that except for the issues mentioned in blog post with Anaconda, it works just as fine as compiling from the source. 😉
Ibn Ahmad
Thanks for this tutorial. It came really handy as I have spent lots of hours running into days trying to install OpenCV despite following your tutorial in some of your other article.
Gracias.
xema
Thanks for this tutorial, but I have a segmentation fault when I want show an image with
cv2.imshow('Output', output)
cv2.waitKey()
QObject::moveToThread: Current thread (0x4ece310) is not the object's thread (0xc95b190).
Cannot move to target thread (0x4ece310)
The same with imwrite. Other functions work fine.
print (cv2.__version__)
returns 3.4.3. I am using python 3.5 with virtualenvwrapper.Mark C
Why Not on Windows?
Abhishek Thanki
Hi Mark,
I tried `pip3 install opencv-contrib-python` on a friend’s laptop (windows 10) and it worked! Just make sure you do it using `virtualenv` and `virtualenvwrapper`to be on the safe side.
Newb
What do you mean by “to be on the safe side”?
Bajjee
Hi,
I am getting following error in my RaspberryPI.
Traceback (most recent call last):
File "pi_object_detection.py", line 84, in
frame = imutils.resize(frame, width=400)
File "/home/pi/.virtualenvs/cv/lib/python3.5/site-packages/imutils/convenience.py", line 69, in resize
(h, w) = image.shape[:2]
AttributeError: 'NoneType' object has no attribute 'shape'
David Hoffman
Hi Bajjee, see this blog post about resolving NoneType errors.
Bajjee
I found a typo in line #74. Line 74 should be commented out and line 75 should be uncommented for RaspberryPI, once i did that, code worked as expected.
Thank you, works great.
Andrew
I got this error too. I have a multiple monitor setup on my mac. It seems to mess with the camera built into my laptop – even photobooth/facetime can’t seem to get the camera working and when I run the python script I get that error. It just can’t find the camera. If I shutdown (not restart) and start up again without the other monitors connected it works.
marco
Hello, I’m trying to follow this apparently beautiful installation on my Raspberri but I stopped immediately because launching the command “pip install virtualenv virtualenvwrapper” at the end I get the following red error “Could not install packages due to an EnvironmentError: [ Errno 13] Permission denied: ‘/usr/local/lib/python3.5/dist-packages/virtualenv.py’
Consider using the `–user` option or check the permissions” How can I resolve this permissions problem?
thank you
Marco
David Hoffman
Hi Marco, it sounds like you’re trying to install the tools into a system folder or maybe something isn’t configured correctly. If you use the –user switch, it should resolve the issue. Try this:
pip install --user virtualenv virtualenvwrapper
marco
hi David, thanks for the answer, I tried the line that you hi suggested and apparently seems to be successful in fact basically says:
Successfully installed pbr-4.2.0 stevedore-1.29.0 virtualenv-16.0.0 virtualenv-clone-0.3.0 virtualenvwrapper-4.8.2
but then launching the command:
source ~/.profile
bash: /usr/local/bin/virtualenvwrapper.sh: File or directory does not exist
from the error above
marco
I forgot, before: successfully installed virtualenv …. in orange there are also these lines:
The script is virtualenv installed in ‘/home/pi/.local/bin’ which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use –no-warn-script-location.
Mike
Make sure you update the bottom line in .bashrc to reflect the path. So it would look like this:
# virtualenv and virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
source /home/pi/.local/bin/virtualenvwrapper.sh
Denis Brion
worked with sudo pip install ….
Richard
I ran into the same problem and up the command permissions with SUDO
Prasanth
Hi Adrian,
i tried to compile Open CV on windows 10 using visual studio 2015, able to perform CMake steps but unable to compile project in Visual Studio. Any idea how to resolve ?
David Hoffman
Hi Prasanth, Adrian doesn’t cover Windows on PyImageSearch. Satya over at LearnOpenCV.com does: Install OpenCV 3 on Windows.
Denis Brion
This is a huge improvements to source compiling for RPi users:
there remain some little details
a) with pip, dependencies such as jasper ane catlas should be already installed via apt-get (I detected I needed libjasper.so; I apt-got its dev counterpart)
b) your demo program assumes there is a video camera connected and working on the RPi. For self teaching, people may try first with already existing videos….
David Hoffman
Thanks for sharing, Denis.
David Killen
Thank you for providing this.
It’s a trivial point to many people here, but it took me a little while to diagnose.
I received the error
[INFO] loading model…
[INFO] starting video stream…
Traceback (most recent call last):
File “real_time_object_detection.py”, line 49, in
frame = imutils.resize(frame, width=400)
File “/home/david/.local/lib/python3.6/site-packages/imutils/convenience.py”, line 69, in resize
(h, w) = image.shape[:2]
AttributeError: ‘NoneType’ object has no attribute ‘shape’
It was, of course, because there is no webcam on my laptop. Once I had amended
vs = VideoStream(src=0).start() # (line 3 in file real_time_object_detection.py)
to point to an mp4 video-file everything worked fine.
David Hoffman
Great job resolving your issue. Adrian also has a blog post about resolving NoneType errors.
Dennis
“…Secondly, some readers, including Anaconda users, have reported problems using GUI functions such as cv2.imshow and cv2.waitKey .”
I use OpenCV on both RPi and Anaconda on my PC. Don’t use PIP to install OpenCV use the conda command:
conda install -c conda-forge opencv
https://anaconda.org/conda-forge/opencv
aarju
after installing cv2 using this(downloaded by above link) command,no error is coming,but this line cap = cv2.VideoCapture(0) returns false.
Adrian Rosebrock
Make sure you have your webcam properly installed and working. What type of camera are you using?
loch
HI adrian
your code work perfectly , earlier i had opencv 3.2.0 where camera release function perfectly
but after upgrading to opencv 3.4.2 to run the programme the camera release( capture.release() ) function not working can u give me a solution to release the camera thank you
Antonio
Hey Adrian,
if I install it via pip on Rasberry Pi, will it included NEON optimizations?
If I install it on my desktop machine, will it include OpenCL support?
suresh
Hi i’m trying to “pip install opencv-contrib-python” in raspberry pi srtetch os. While installing i’m getting “Could not find a version that satisfies the requirement opencv-contrib-python (from versions: )No matching distribution found for opencv-contrib-python..” Please help me with the error.
David Hoffman
Hi Suresh, which hardware (Pi 3B, Pi 3B+, etc.) are you using?
hutu
Hi David,
I solved this issue by Ben’s FAQ in github: adding the piwheels index to /etc/pip.conf.
as i’m guessing piwheels is by default missing inside stretch lite.
add below lines to /etc/pip.conf :
–>
[global]
extra-index-url=https://www.piwheels.hostedpi.com/simple
John
Thanks hutu!
This was exactly the solution.
Pedro
This was exactly my solution to error ERROR: Could not find a version that satisfies the requirement opencv-contrib-python (from versions: none)
ERROR: No matching distribution found for opencv-contrib-python on Raspi Zero W
File /etc/pip.conf doesent exists, I create it and put his code and after this I can install
srujan
Hey Pedro,
I am using a headless Raspbian stretch. I am facing this error and couldn’t find the etc/pip.conf. Could you help me with the instructions on how to create this file? Thanks
Tomas Cechura
Hi, I experienced the same behaviour on my RPi 3B+ with latest Raspbian Stretch Lite – any suggestions?
Kevin
I had this problem as well on the RPi 3B+ and I found out that my pip version was just too outdated. Try running
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python get-pip.py
$ sudo python3 get-pip.py
even if you already have pip installed that should get it up to date.
Adrian
Hi! Adrian, in the first place i have installed opencv 3.4.1 with all features like “Gstreamer” already and after to update with “pip install” comand to opencv 3.4.3 all thats features was disable….
you know how to set this settings again like “-with Gstreamer=ON” or something?
Antoni
I’m having exactly the same error tha Suresh. Trying to install in Raspbian strech in 3B+ with Python 3.7.
Adrian Rosebrock
Which Raspberry Pi hardware are you using? Can you confirm your exact Raspbian Stretch version as well? I would suggest trying on a fresh install of Raspbian to see if that resolves the issue.
Antonio Bardaji Cuso
Hi Adrian,
I’m using latest version of Raspberry Pi 3B+ with latest version of Raspbian Stretch 9.4. with python 3.7.
Trying to install Opencv using pip. I got the same message than Suresh: “Could not find a version that satisfies the requirement opencv-contrib-python (from versions: )No matching distribution found for opencv-contrib-python..”
Any Idea?
Adrian Rosebrock
See my reply to Simeon.
pite
try using pip3
Adrian Rosebrock
If you’re trying to customize the install you should compile and install OpenCV from source.
hutu
Hi Adrian,
the tutorial is not working for stretch lite which is popular for headless use of rpi3 b/b+. still need a lot walk-around. whether you can check also as it’s quite advanced topics for new comer.
thanks.
hutu
Hi Adrian,
I’m wrong, stretch lite for vision related application is useless as without gui/display output to show result 🙁
sorry I’m new to this area…
Adrian Rosebrock
Stretch Lite doesn’t have a window manager which is why you don’t see any output images. You would need to install a window manager and/or install X11 and then SSH into your Pi with X11 forwarding enabled.
Ulises Flynn
After installing virtualenv in osx:
$ which virtualenvwrapper.sh
/Library/Frameworks/Python.framework/Versions/3.6/bin/virtualenvwrapper.sh
$sudo ln /Library/Frameworks/Python.framework/Versions/3.6/bin/virtualenvwrapper.sh /usr/local/bin/virtualenvwrapper.sh
This fixes the virtualenvwrapper.sh not being found in the .bash_profile.
Nigel
As usual a well written article and highly useful article.
I see that virtualenv is being used. But python offers a virtual environment venv. Can one use this or should one stick to virtualenv?
Adrian Rosebrock
I personally prefer virtualenv and virtualenvwrapper together but it’s your personal preference.
Dennis Mabrey
On the Raspberry PI I kept receiving errors when I would import cv2 in python3.
It would say: ImportError: libcblas.so.3: cannot open shared object file: No such file or directory
I did find the fix for it here: https://github.com/amymcgovern/pyparrot/issues/34#issuecomment-379557137
I had to install these dependencies:
sudo apt-get install libatlas-base-dev
sudo apt-get install libjasper-dev
sudo apt-get install libqtgui4
sudo apt-get install python3-pyqt5
Adrian Rosebrock
Thanks for sharing Dennis!
cbasavaraj
Hi, I installed all the above dependencies. Yet I now get ImportError: libImath-2_2.so.12
But to be noted that I am using Stretch Lite and did pip install opencv-python-headless
Brian H Wilson
I am having the same problem. Same set up. Stretch Lite
Using python3 in a virtualenv
Did not make any difference, headless or not, contrib or not, same thing.
Avery Uslaner
When you run into issues like these, it’s helpful to search your package manager using the command:
$ sudo apt-cache search packagename
So in this case, you would find that you need to do:
$ sudo apt-get install libilmbase12
Santiago
Thanks for sharing friend! it works for me.
Harsh
Other than above dependencies, I have installed ffmpeg to fix importerror: libswscale.so.4
sudo apt-get install ffmpeg
Simeon
Hi Adrian. I’m getting an error saying no matching distribution found for opencv-contrib-python. Trying to installl it on the raspberry pi with Ubuntu LX OS. Does this mean I need to install from source?
Adrian Rosebrock
Yes, if there is no matching distribution then there are no pre-compiled versions of OpenCV you can install via pip. You would need to compile OpenCV from source. Be sure to refer to my OpenCV install tutorials to help you get started.
pite
pip gave me that error but pip3 worked
Angenieux
Dear All,
I’m trying to “pip install opencv-contrib-python” on a RASPBERRY PI ZERO W (RASPBIAN STRETCH WITH DESKTOP).
I have the following issue ” Could not find a version that satisfies the requirement opencv-contrib-python (from versions: ) No matching distribution found for opencv-contrib-python
”
Any help is welcome.
Last time I compiled opencv on raspberry pi it took to long time. 😉
Thanks a lot
Adrian Rosebrock
It unfortunately means there are no pre-compiled versions available for your Raspberry Pi Zero. You will need to compile and install OpenCV from source.
RD
Hi
I tried the tutorial but had a problem in the first go. I was not able to install pip.
I installed using the sudo apt command
$ sudo apt install python3-pip
This installed pip for me. But I realized that the pip was installed for python3 and not for python 2. That means I had to use pip3 instead of pip to install opencv.
The following code (as mentioned in the tutorial) did not work for me
$ sudo pip install opencv-contrib-python
But when I use pip3 instead of pip then the installation runs fine.
$ sudo pip3 install opencv-contrib-python
Is this something that has only happened for me or has someone else also faced the same problem. Form what I read online, pip3 is for python3 and pip is for python2
Jafet Mora
Hello, I installed opencv in my RPi Zero (Raspbian Stretch) by means of pip, my current version is 3.4.3. and when trying to compile the “pi_object_detection.py” code located in the download area, with python and python3 after the program shows “[INFO] loading model …”
“[INFO] starting process …”
“[INFO] starting video stream …”
show this:
Illegal instruction
I do not know if it should be a problem with the opencv installed from piwheels, or if it is something in the code that needs to be changed, and if not, could anyone help me install version 3.3+ in the RPi Zero from the source ?
Adrian Rosebrock
Can you insert a few “print” statements to debug exactly which line is causing execution to stop? I’m willing to bet it’s “imutils.resize”. For some reason the Pi Zero doesn’t like the
inter
flag set tocv2.INTER_AREA
. If you change it tocv2.INTER_LINEAR
it should work.Kevinl7778
The pip install went smooth, but I cant find the data folder containing the haarcascade clasifier and other stuff.
Any idead as to where it would be on the raspbian pixel?
Adrian Rosebrock
The pip install of OpenCV is a pre-compiled binary. It does not contain the additional directories from a clone of the GitHub repo. You can find what you’re looking for in OpenCV’s GitHub.
KEVINL7778
I found them here: (PIP3 install)
/home/YOURNAMEHERE/.local/lib/python3.5/site-packages/cv2/data
I will testit out tonight.
Thanks for all of the work you list on the site and good luck with the sale.
Kevin
Adrian Rosebrock
Thanks Kevin!
John
Virtual wrapper is also missing a distribution. Worthless advice here. Method doesn’t work.
Adrian Rosebrock
Hey John — that actually sounds like a problem with your local dev environment and potentially even a network issue. Without knowing more about your dev environment neither myself nor anyone can help you. If you are going to take the time to write a comment on my blog I would also suggest you take the time to describe your environment and any error you are getting, otherwise I’m afraid we are both wasting our time which is something I do not want 🙁
Colin
My robot Raspberry Pi brain has all of its code written in Python 2.7 and it would be a major task to rewrite in Python 3. Does this pip installation work for 2.7? If so I would be grateful for pointers as to what to change.
Thanks.
Adrian Rosebrock
It should although I no longer support Python 2.7 officially here on PyImageSearch. You would just want to create a Python 2.7 virtual environment instead of a Python 3 one:
All steps should be the same.
Heiko Zschimmer
Is there a way to select picam?
it seems that the default settings use a USB cam?
Adrian Rosebrock
I would instead suggest you use my VideoStream class which works with both USB cameras and the Raspberry Pi camera module.
hotdog
i want to know why i always install the opencv in the python2 not in the python3, thanking you!
Adrian Rosebrock
Are you using Python virtual environments? Which version of Python are you trying to install OpenCV for?
Hasan
Hi Dr.Adrian,
I am new with OpenCV and I am using Win 10.
So, please
How I can install opencv-contrib-python and continue with Opencv course.
Thank
Yilliang Peng
Hi Adrian! I just wanna ask you if there is any difference with “make -j4” and “pip install opencv-contrib-python” because I installed it first with make -j4 and it cause and error while with pip it works perfectly. Is it going to be fine?
Adrian Rosebrock
Keep in mind that the opencv-contrib-python module is NOT the same as compiling and installing from scratch. If you install via pip you will not have the NONFREE modules from the contrib package (such as SIFT and SURF).
If you run into any errors related to the NONFREE modules when executing your code you will know it’s because of the pip install (and then you’ll need to compile OpenCV from source).
Hasan
Does n’t matter Dr., I think that I get the solution. Thanks
Adrian Rosebrock
Congrats on getting OpenCV installed, Hasan!
Sam T
HI , this is the third time i am compiling. I dont know why the root folder is using all the available space of the sd card 16gb
and the compilations stops with a fatal error that there is no space.
Please help me out.
Adrian Rosebrock
Just to clarify, are you compiling OpenCV from source? Or are you installing OpenCV via pip? Installing OpenCV via pip shouldn’t use up much disk space so I get the impression that you’re compiling from source — but you’re commenting on a pip install post. Could you clarify?
Yaya
Hello
I got this error when import cv2 module
“ImportError: numpy.core.multiarrayfailed to import”
How can I fix it?
Thanks
Adrian Rosebrock
It sounds like you haven’t installed NumPy yet:
Shymaa Abo Arkoub
can not we install it on window?
Adrian Rosebrock
You can install OpenCV Windows but I do not officially support Windows here on the PyImageSearch blog. If you are interested in computer vision and OpenCV I highly suggest you use a Unix-based OS such as Ubuntu or macOS.
Ebi
Hey, I have installed opencv2 on my windows (in cmd when I go to python and import cv2, there is no error), but how in my project doesn’t know it? I have to install it by “pip install opencv-python”. I can not install it globally?
Adrian Rosebrock
Are you using Python virtual environments? If so, I advise installing OpenCV into the virtual env (not globally).
Brad
Thanks for a super useful resource Adrian!
I’m trying to understand why images are being resized to 300 x 300 in pi_object_detection.py. I was under the impression that MobileNet expects images of 224 x224? What am I missing?
Also, would it not be more performant to set image width and height on the original video stream, rather than resizing each frame for the detection process?
Adrian Rosebrock
Actually, the MobileNet SSD trained on the COCO dataset accepts 300×300 inputs, not 224×224 ones. You could also set the dimensions via the video stream as well.
Zubair Ahmed
Hi Adrian
Thanks for writing this, I just followed it to install OpenCV on my new Raspberry Pi 3B+
Looks like you need to also install sudo apt-get install libjasper-dev
Without this I was getting an import error ‘libjasper.so.1: cannot open shared object file: No such file or directory’
Chip Williams
install of opencv-contrib-python with pip on RPi 3B+ did not work.
– Running Raspbian Stretch clean install
– Have installed virtual environments and that seems to be working fine
– The installation procedure completed successfully
– I did a workon cv to get into the virtual environment
– A help() modules shows that cv2 is present
– import cv2 results in error message:
“ImportError: libcblas.so.3: cannot open shared object file: No such file or directory”
Where was that library supposed to come from? Thanks.
Chip Williams
OK. So had to apt-get install libatlas3-base and then libjasper1.
Chip Williams
So having worked through this process I can now run the demo on the RPi 3B+ but my output does not look like what Adrian posted above. My frame is larger vertically than the image and if I run my mouse over the top of the image the image coordinate and the RGB value are displayed at the bottom of the frame about a third truncated. Then there is also a dead space between the top of the image and the bottom of the title bar. If I click in that dead space it zooms in and displays the RGB value on every pixel. This action is inconsistent with what cv2.imshow() has done on other platforms. Anybody have an idea what entity has added all this (unwanted) extra functionality? How do you get rid of it?
Adrian Rosebrock
This seems like a GUI-related issue with the pre-built OpenCV binary. What version of OpenCV was installed?
Akshay Chaturvedi
Hi Adrian,
Great Article and big fan. I am having this very weird problem. After successful installation on every package and doing every step properly. I just ran a file(python file.py) with command cv2.imread(‘Download.jpg’) and it says AttributeError :module ‘cv2’ has no attribute ‘imread’
Also after rebooting the Pi and running the python shell and import cv2 gives the same error.
I am really looking for some help desperately.
Adrian Rosebrock
That is incredibly, incredibly strange. What OS were you tryin to install OpenCV on?
kilari Parthasarathy
Hi, I was reading this article and knew how install opencv using pip in different operating systems. can we install the same in windows.
Adrian Rosebrock
Potentially, but I’m not sure. I do not support Windows here on the PyImageSearch blog (see the FAQ).
vindo
hey i already followed your tutorial and when i tried to import cv2 in terminal it said no module named cv2
Adrian Rosebrock
Make sure you use the “workon” command to access your Python virtual environment first.
Tiago
Hi Adrian,
I’m having the same issue. I’ve followed your steps and I’ve created a virtualenv. Once I have it activated, and after installing OpenCV, I run ‘python’ and then ‘import cv2’ and I get the same ‘no module named ‘cv2” message. Am I missing something?
Thanks
Tiago
Adrian Rosebrock
Check the output of the pip install — there may be an error message you are missing.
Wistan M.
Hello Adrian,
I have the same error as mentionned in this mini-thread. I followed every line for Raspberry Pi install, no error at all until the ‘no module named ‘cv2” when importing cv2. The OpenCV install command says it’s successfully installed, and yet I can’t find any trace of opencv in my virtual env. Any ideas ?
Thanks,
Wistan.
Adrian Rosebrock
Verify that you are in the Python virtual environment using the “workon” command and then use “pip” to install. Additionally, do not use “sudo pip install” as that will bypass the virtual environment and install on the system Python rather than the virtualenv Python.
David Joseph T
A tutorial on how to install OpenCV on windows machine would have been great to, cos i use a windows pc, thanks
Adrian Rosebrock
Sorry, I don’t cover Windows nor support Windows here on the PyImageSearch blog for reasons discussed in the FAQ.
dan b
Having the problem referred to above where PIP cannot fine version of opencv-contrib-python.
I have raspi v10 (buster)
I have tried the two potential solutions described above, editing the /etc/pip.conf file to replace the existing entry (ending the line w … hostedpi.com/simple
And also tried the PIP3 variant suggested with the same error resulting.
Please help. Trying to compile opencv has failed with various errors in libraries/cmake/make etc, so compiling is not an option. Is this an issue with raspi 10?
dan b
Cancel that request. The problem was indeed the version switch for raspian (version 10 does not work; version 9 works fine.
Note that the raspian NOOBS main page does a poor job explaining which version of raspian you actually get when you click on the download button. Now that version 10 is the default, maybe you could add a line in your tutorial telling people to check the version of raspian. A simple $ cat /etc/os-release at the terminal prompt would have saved me a few hours of frustration.
Thanks for all the fine work you do for the opencv community.
Adrian Rosebrock
Thanks Dan. Just to add an additional comment — I don’t recommend using NOOBS. Use the standard Raspbian install.
BBC_Basic
HI Dan,
I am new to Raspberry Pi and don’t know where to find the switch that you refer too. I ran $ cat /etc/os-release and find that i am running version 10.
Can I change this or is it a reinstall?
A.B
I actually spoke too soon but was able to recover from another install issue for opencv, this time related to numpy.
If it complains about the version of numpy it wants to install is not valid for python 3.4.4 (see previous post), you can check which version is appropriate for 3.4.4 from https://www.piwheels.hostedpi.com/simple/numpy/.
Since numpy 1.16.4 is the appropriate version for python 3.4.4, you can install it via
`pip3 install numpy==1.16.4 -vvv`
Then redoing the command `pip3 install opencv-contrib-python` (which again is going to install the version appropriate for the tags listed by the `pip debug` command) should be successful.
Daniel Ferguson
Thanks so much for this info, and for your articles in general.
If I use this installation method, can I cmake third-party libraries (e.g. BackgroundSubtractorCNT) that reverence OpenCV? It seems this method does not create any OpenCV environment variables and does not have an OpenCVConfig.cmake file.
Adrian Rosebrock
Unfortunately you will need to compile OpenCV from source.
Jon H
Thank you Adrian!
It’s working on Raspbian Buster on a Pi 4, but to close out I x out of terminal and to run it again I have to start from
source ~/.profile
mkvirtualenv cv -p python3
workon cv
etc.
What is the right way to end so it doesn’t wipe my virtualenv?
Adrian Rosebrock
You can add those commands to your “.profile” or “.bashrc” file so they are automatically loaded each time you own a new terminal.
jack
Let me know Raspberry pi image name ?
In my case, rasberian buster image.
after boot, I checked python version. it is 3.7 but your documentation is 3.6
so I ask you that I wrote above.
Ash
Just FYI for anyone that is getting the error “/usr/local/bin/virtualenvwrapper.sh: No such file or directory” after installing Virtualenv on Ubuntu 18. It appears that it’s now installed here: “~/.local/bin/virtualenvwrapper.sh” 🙂
bari
thanks alot this is a very easy way .
Adrian Rosebrock
Thanks, I’m glad you enjoyed it!
David Hoffman
Be sure to search the blog post for the 2019-11-21 Update if you are encountering an
"undefined symbol: __atomic_fetch_add_8"
error while pip installing OpenCV 4 onto your Raspberry Pi 4B running BusterOS. A workaround has been added to the blog post. A big thanks goes out to those that notified us of the error.Jere
This was helpful. Thanks
Adrian Rosebrock
You are welcome, I’m glad it helped you!
Nob
Thanks a lot ! Everything went well.
I changed below for my Raspberry Pi 4.
” libhdf5-100 -> libhdf5-103 ”
Because, my “apt-get” couldn’t find libhd5-100.
Thanks again.
Raspberry Pi 4 Model B Rev 1.2
Raspbian GNU/Linux 10 (buster)
Python 3.7.7
Adrian Rosebrock
Thanks for sharing!
Veda praneeth
Cant we do OpenCV on a laptop I mean on windows as you are specifying as ubuntu, mac os, raspberry pi
Adrian Rosebrock
Yes, but I do not officially support Windows on the PyImageSearch blog. I recommend you use a Unix-based machine to learn Computer Vision and Deep Learning.