As I mentioned last week, OpenCV 3.0 is finally here!
And if you’ve been paying attention to my Twitter stream, you may have noticed a bunch of tweets regarding installing OpenCV on OSX and Ubuntu (yep, I’ve been tweeting a lot lately, but that’s just because I’m so excited about the 3.0 release!)
To celebrate OpenCV 3.0, I have decided to perform a series of blog posts that detail how to install OpenCV 3.0 on both Python 2.7+ and Python 3+.
We’ll also be performing these Python 2.7 and Python 3+ installations on a variety of platforms including OSX, Ubuntu, and yes, the Raspberry Pi.
As I’m sure you already know, OpenCV has never been an effortless library to install. It’s not like you can let pip
or easy_install
to the heavy-lifting for you. In most cases you’ll be pulling down the repo, installing prerequisites, compiling by hand, and hoping that your installation goes smoothly.
With OpenCV 3.0 it doesn’t get any easier — and there are definitely some caveats and gotchas that you need to look out for (such as the opencv_contrib repository — without it, you’ll be missing out on some important features, such as SIFT, SURF, etc.)
But don’t worry, I’ve got you covered! Just keep following along with the PyImageSearch blog and I promise these tutorials will get you up and running with OpenCV 3.0 in no time.
We’ll go ahead and kick-off our OpenCV 3.0 install fest by installing v3.0 with Python 2.7+ bindings on the OSX platform.
If you’re an Ubuntu or Raspberry Pi user, be sure to keep an eye on PyImageSearch as I’ll be posting OpenCV 3.0 install instructions for Ubuntu and the Raspberry Pi as well.
A quick note before we get started: While OpenCV 3.0 is indeed compatible with Python 3+, most computer vision developers are still using Python 2.7 (since OpenCV 2.4.X is only compatible with Python 2.7). If you’re a Python 3 user and excited to give the bindings a try — don’t worry! I’ll be covering OpenCV 3.0 and Python 3+ installation in a future tutorial. But for now, let’s stick with what we know and use Python 2.7.
UPDATE: The tutorial you are reading now covers how to install OpenCV 3.0 with Python 2.7 bindings on OSX Yosemite and below. This tutorial still works perfectly if you are using OSX Yosemite or prior, but if you want to install OpenCV on the newer El Capitan and macOS Sierra please use this freshly updated tutorial.
How to Install OpenCV 3.0 and Python 2.7+ on OSX
This is our first tutorial in our OpenCV 3.0 install-fest series. In this tutorial I’ll be detailing how to install OpenCV 3.0 and Python 2.7+ on the OSX operating system — I’ll be covering Python 3+ in a future post.
Let’s go ahead and dive into the OpenCV 3.0 and Python 2.7+ install instructions.
Step 1:
The first step we need to do is install Xcode, which is a combination of IDE and software development tools for developing applications on the OSX and iOS platforms — most of us already have Xcode installed.
But if you don’t, you’ll want to open up the App Store application and search for Xcode. From there, just click Get and Install App (and when prompted, you’ll need to enter your Apple ID username and password):
Step 2:
Now that Xcode is installed, we need to install Homebrew, which is labeled as “The missing package manager for OSX” (and they really are not joking about that one). Think of Homebrew as an (almost) equivalent of apt-get for Ubuntu.
To install Homebrew, simply head to the Homebrew website and simply copy and paste the command underneath the “Install Homebrew” section into your terminal:
$ cd ~ $ $ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Now that Homebrew is installed, you’ll need to update it and grab the latest package (i.e. “formula”) definitions. These formula are simply instructions on how to install a given package or library.
To update Homebrew, simply execute:
$ brew update
Step 3:
It’s bad form to use the system Python as your main interpreter. And this is especially true if you intend on using virtualenv
and virtualenvwrapper
(which we will be).
Let’s go ahead and use Homebrew to install our user-specific version of Python 2.7:
$ brew install python
Note: This tutorial will be covering how to install and setup OpenCV 3.0 with Python 2.7. I will be covering how to install OpenCV 3.0 with Python 3+ later this month.
However, before we proceed, we need to update our PATH
in our ~/.bash_profile
file to indicate that we want to use Homebrew packages before any system libraries or packages. This is an absolutely critical step, so be sure not to skip it!
Open up your ~/.bash_profile
file in your favorite editor (if it does not exist, create it), and append the following lines to the file:
# Homebrew export PATH=/usr/local/bin:$PATH
From there, reload your ~./bash_profile
file to ensure the changes have been made:
$ source ~/.bash_profile
As a sanity check, let’s confirm that we are using the Homebrew version of Python rather than the system one:
$ which python /usr/local/bin/python
If your output of which python
is /usr/local/bin/python
, then you are indeed using the Homebrew version of Python. And if your output is /usr/bin/python
, then you are still using the system version of Python — and you need to go back and ensure that your ~/.bash_profile
file is updated and reloaded correctly.
Again, this is a very important step, so be sure not to skip it!
Step 4:
Alright, time to get virtualenv and virtualenvwrapper installed and configured correctly. These packages allow us to create separate Python environments for each project we are working on. This is especially useful if you have projects that require different (or conflicting) versions of a given library.
It’s important to note that virtualenv
and virtualenvwrapper
are by no means required to install OpenCV 3.0 and Python 2.7+ on OSX. However, you really should be using these packages when doing Python development. It’s cleaner. Easier to maintain. And well worth the upfront effort.
Anyway, to install virtualenv
and virtualenvwrapper
, just execute the following command:
$ pip install virtualenv virtualenvwrapper
Again, we need to update our ~/.bash_profile
file by appending the following two lines:
# Virtualenv/VirtualenvWrapper source /usr/local/bin/virtualenvwrapper.sh
After updating the ~/.bash_profile
file, we need to reload it:
$ source ~/.bash_profile
At this point, both virtualenv
and virtualenvwrapper
are installed correctly, so we can create our cv
virtual environment:
$ mkvirtualenv cv
This command will create a new Python environment that is entirely sequestered from our system and Homebrew Python installations. The cv
virtual environment is where we’ll be doing all of our computer vision development (and not to mention, compiling OpenCV 3.0 with Python 2.7+ support).
Step 5:
Now we can start installing some Python packages. We need to install NumPy since the OpenCV Python bindings represent images as multi-dimensional NumPy arrays:
$ pip install numpy
Step 6:
Up until this point we have been mainly focusing on actually setting up and configuring our development environment to compile and install OpenCV — here is where the real work starts.
First, we’ll use brew to install the required developers tools, such as the wonderful CMake utility:
$ brew install cmake pkg-config
And here we are going to install the necessary image I/O packages. These packages allow you to load various image file formats such as JPEG, PNG, TIFF, etc.
$ brew install jpeg libpng libtiff openexr
And finally, let’s install libraries that are used to optimize various operations within OpenCV (if we so choose):
$ brew install eigen tbb
Step 7:
Alright, our system is all setup — time to compile and install OpenCV 3.0 with Python 2.7+ support.
The first thing we’ll do is change directory to our home directory, followed by pulling down OpenCV from GitHub, and checking out the 3.0.0
version:
$ cd ~ $ git clone https://github.com/Itseez/opencv.git $ cd opencv $ git checkout 3.0.0
Update (3 January 2016): You can replace the 3.0.0
version with whatever the current release is (as of right now, it’s 3.1.0
). Be sure to check OpenCV.org for information on the latest release.
Unlike previous versions of OpenCV that were (essentially) self-contained, we need to pull down the extra opencv_contrib repo from GitHub as well. The opencv_contrib
repo which contains extra modules for OpenCV, such as feature detection, local invariant descriptors (SIFT, SURF, etc.), text detection in natural images, line descriptors, and more.
$ cd ~ $ git clone https://github.com/Itseez/opencv_contrib $ cd opencv_contrib $ git checkout 3.0.0
Again, make sure that you checkout the same version for opencv_contrib
that you did for opencv
above, otherwise you could run into compilation errors.
Note: We don’t have to pull down the opencv_contrib
repo if we don’t want to. OpenCV will compile and install just fine without it. But if you compile OpenCV without opencv_contrib
, be warned that you’ll be missing out on some pretty important features, which will become very obvious, very fast, especially if you’re used to working with the 2.4.X version of OpenCV.
Step 8:
Let’s setup our OpenCV build by creating the build
directory:
$ cd ~/opencv $ mkdir build $ cd build
Where we’ll use CMake to configure our build:
$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local \ -D PYTHON2_PACKAGES_PATH=~/.virtualenvs/cv/lib/python2.7/site-packages \ -D PYTHON2_LIBRARY=/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework/Versions/2.7/bin \ -D PYTHON2_INCLUDE_DIR=/usr/local/Frameworks/Python.framework/Headers \ -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON \ -D BUILD_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules ..
There are some very important options we are supplying to CMake here, so let’s break them down:
CMAKE_BUILD_TYPE
: This option indicates that we are building a release binary of OpenCV.CMAKE_INSTALL_PREFIX
: The base directory where OpenCV will be installed.PYTHON2_PACKAGES_PATH
: The explicit path to where oursite-packages
directory lives in ourcv
virtual environment.PYTHON2_LIBRARY
: Path to our Hombrew installation of Python.PYTHON2_INCLUDE_DIR
: The path to our Python header files for compilation.INSTALL_C_EXAMPLES
: Indicate that we want to install the C/C++ examples after compilation.INSTALL_PYTHON_EXAMPLES
: Indicate that we want to install the Python examples after complication.BUILD_EXAMPLES
: A flag that determines whether or not the included OpenCV examples will be compiled or not.OPENCV_EXTRA_MODULES_PATH
: This option is extremely important — here we supply the path to theopencv_contrib
repo that we pulled down earlier, indicating that OpenCV should compile the extra modules as well.
Update (3 January 2016): In order to build OpenCV 3.1.0
, you need to set -D INSTALL_C_EXAMPLES=OFF
(rather than ON
) in the cmake
command. There is a bug in the OpenCV v3.1.0 CMake build script that can cause errors if you leave this switch on. Once you set this switch to off, CMake should run without a problem.
Whew, that was a lot of options.
Trust me, it’s a lot easier installing OpenCV 3.0 on Ubuntu where these options are automatically determined via CMake for us.
But when using OSX you’ll need to explicitly define the PYTHON2_PACKAGES_PATH
, PYTHON2_LIBRARY
, and PYTHON2_INCLUDE_DIR
yourself. It’s a real pain, but if you don’t, your compile will fail.
Here’s an example of what my CMake output looks like:
Notice how the Python 2 Interpreter, Libraries, numpy version, and packages path have been correctly picked up.
You’ll also want to make sure that python2
is in the list of modules To be built, like this:
If it python2
is not in this list, and is in the Unavailable list, then you need to go back to the CMake step and ensure that you have correctly supplied your PYTHON2_PACKAGES_PATH
, PYTHON2_LIBRARY
, and PYTHON2_INCLUDE_DIR
.
Now that CMake has properly configured the build, we can compile OpenCV:
$ make -j4
Where the 4 can be replaced with however many cores you have available on your processor. Here’s an example of OpenCV compiling on my system:
And assuming that OpenCV compiled without error, you can now install it on your OSX system:
$ make install
If you get an error message related to permissions (although that really shouldn’t happen), you’ll need to run the install command as sudo
:
$ sudo make install
Step 9:
Assuming you’ve made it this far, let’s perform a sanity check and ensure OpenCV is installed:
$ cd ~/.virtualenvs/cv/lib/python2.7/site-packages/ $ ls -l cv2.so -rwxr-xr-x 1 adrian staff 2013052 Jun 5 15:20 cv2.so
Sure enough, we can see that OpenCV has been installed in our cv
virtual environment’s site-packages
directory!
As a quick note, you’ll be able to find the cv2.so
file (which is your OpenCV bindings) in your build/lib
directory as well.
Let’s verify our install by firing up a shell and importing OpenCV:
(cv)annalee:~ adrianrosebrock$ python Python 2.7.8 (default, Jul 31 2014, 15:41:09) [GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import cv2 >>> cv2.__version__ '3.0.0'
Doesn’t that 3.0.0
look nice?
Congrats, you have now installed OpenCV 3.0 and Python 2.7+ on your OSX system!
Step 10:
After all this work, let’s give our OpenCV 3.0 install a test drive!
Most of my work in computer vision involves image search engines, or more formally, Content-based Image Retrieval. A critical step of CBIR is extracting features to quantify and abstractly represent the contents of an image.
OpenCV 3.0 has numerous updates and changes, but perhaps my personal favorite is an implementation of AKAZE features — Fast Explicit Diffusion for Accelerated Features in Nonlinear Scale Spaces by Alcantarilla et al.
Since Jurassic World was just released (and Jurassic Park is my favorite movie of all time), let’s explore how we can compute and extract AKAZE features from the following image:
Open up a new file, name it test_akaze.py
, and insert the following code:
# import the necessary packages from __future__ import print_function import cv2 # load the image and convert it to grayscale image = cv2.imread("jurassic_world.jpg") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow("Original", image) # initialize the AKAZE descriptor, then detect keypoints and extract # local invariant descriptors from the image detector = cv2.AKAZE_create() (kps, descs) = detector.detectAndCompute(gray, None) print("keypoints: {}, descriptors: {}".format(len(kps), descs.shape)) # draw the keypoints and show the output image cv2.drawKeypoints(image, kps, image, (0, 255, 0)) cv2.imshow("Output", image) cv2.waitKey(0)
And then execute it via:
$ python test_akaze.py keypoints: 762, descriptors: (762, 61)
Assuming you have download the jurassic_world.jpg
image and placed it in the same directory as your test_akaze.py
script, you should see the following output:
Notice how we have been able to detect keypoints and extract AKAZE features in our image!
Obviously we need to do a lot more work than this to build a useful project using AKAZE features — but this example demonstrates that (1) our OpenCV 3.0 install is working, and (2) we are able to use a unique OpenCV 3.0 feature using Python 2.7.
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
OpenCV 3.0 is finally here! And to celebrate the OpenCV 3.0 release, we are going to performing an OpenCV 3.0 install-fest for both Python 2.7+ and Python 3+ on a variety of operating systems including OSX, Ubuntu, and the Raspberry Pi!
This article kicked-off the install fest by detailing how to setup and install OpenCV 3.0 and Python 2.7+ on the OSX operating system.
Next week, we’ll be moving over to Ubuntu and detailing the instructions to get OpenCV 3.0 and Python 2.7 installed on Ubuntu 14.04+ (hint: it’s much easier than OSX).
Anyway, I hope you enjoyed this post and found it useful!
Please consider subscribing to the PyImageSearch Newsletter by entering your email address in the form below — I’ll be sending out updates as new OpenCV 3.0 + Python install instructions are released!
Join the PyImageSearch Newsletter and Grab My FREE 17-page Resource Guide PDF
Enter your email address below to join the PyImageSearch Newsletter and download my FREE 17-page Resource Guide PDF on Computer Vision, OpenCV, and Deep Learning.
Jason
This is a great tutorial. This helps much more than the homebrew formula built for opencv 3.0 did.
Only comments are, Line 6 of the cmake command is missing a “\” at the end of it so it executes prematurely when copied and pasted.
Also, a question. I am trying to follow the tutorial on this page.
http://docs.opencv.org/master/db/d5c/tutorial_py_bg_subtraction.html
createBackgroundSelectorMOG and createBackgroundSelectorGMG do not seem to be working in OpenCV 3.0 as installed here. I would really like to try GMG on an existing project, and that existing project fails now because MOG seems to be removed. Is this on purpose or am I missing a step to connect these and other OpenCV functions?
Adrian Rosebrock
Hey Jason, thanks for the comment. I fixed the command and added in the trailing slash, so that shouldn’t be a problem anymore.
As for your question, try using
cv2.createBackgroundSubtractorMOG2
. I’m not sure wherecv2.createBackgroundSubtractorMOG
(notice the lack of the trailing “2”) went, but it’s definitely not in the 3.0 release with Python bindings. I know both are part of the 2.4.11 release though, just with slightly different function names.The GMG based method is not part of the Python bindings for the 3.0 release (again, I’m not sure why). I think it’s available in one of the RC or beta releases (not positive though).
Also, which version of Python are you using? I’ve noticed that not all of the bindings are compiled and installed when using 2.7 vs. 3.
Jason
Thank you for getting back to me. I never upgraded to Python 3, Python 2.7.10 is what I am using and has always satisfied my needs. I’m looking forward to more Python bindings from OpenCV in the future.
Patrick
I’ve always used brew install opencv to get v2. Is it just a matter of time before v3 is that easy, or has something changed to prevent an easy install? Or have I been doing it wrong.
Adrian Rosebrock
There is a brew formula that has been released about 4 days ago for OpenCV 3.0, you can find it here. The biggest issue is the customizability of the opencv_contrib package which now contains important features such as SIFT, SURF, etc. which were part of 2.4.X, but have been marked as optional in 3.0, mainly related to patent reasons.
Furthermore, by compiling from source you can install to a custom location and run multiple versions of Python and OpenCV at the same time! This is especially important since OpenCV 3.0 was just released and we’re still finding bugs and backwards compatibility issues. With brew, you won’t be able to do this.
Casey
First, thanks for the helpful guide. I was able to get OpenCV 3.0 running in my virtual environment (running OSX by the way) after some tweaking of the Cmake options. Specifically, I had to turn off build_opencv_videoio for an error free compilation. I would still like to get the video I/O capabilities. Do you know what other dependancies I need? Perhaps you could post your entire Cmake output.
Adrian Rosebrock
Hi Casey, OpenCV has a lot of video I/O capabilities, is there a specific one that you are looking for or just the general ability to read video files? In my case, I did not have to install any extra dependencies related to video I/O and I can access the webcam and read frames from video without an error. However, that all said, look into the (optional) ffmpeg dependency which should bring in many, many packages related to video I/O.
Yong Yuan
Is it possible to install the OpenCV 3.0 with Homebrew by “brew install opencv3”? I want to using the OpenCV with python or with C plus plus in Xcode.
Adrian Rosebrock
Indeed it is! I’ll be doing another set of followup posts regarding installing OpenCV 3.0 with Homebrew within the next few weeks. These posts are simply to help readers who are interested in compiling and installing OpenCV 3.0 from source.
Mark
But will it include the additional plugins like ‘amakaze’ etc?
Adrian Rosebrock
Hey Mark, all extras from the opencv_contrib repository will be installed. Please see Step 7 where we clone down the git repos for more information.
Joseph
What are your views on using Anaconda? I was able to download the required packages through ‘conda install’ but the only opencv that’s available for download is version 2.4.8. Have you used Anaconda before and if so, is there any way to upgrade it to version 3.0.0?
Adrian Rosebrock
Continuum’s Anaconda is a really great tool — but you really won’t see me post about it here on PyImageSearch. The Continuum team and myself had a falling out about a year ago, and because of that, I don’t use their products.
Joseph
Thank you for the reply! I also apologize for any negative sentiments I brought with the comment. I was just debating whether I should just go with virtualenv and homebrew python to work with opencv 3.0.0.
Adrian Rosebrock
No worries Joseph, there were no negative sentiments 🙂 I’ll be doing a blog post within the next 3-4 weeks on Homebrew + Python + OpenCV 3 as well.
Daniel Revier
Hi Adrian,
Any progress on the Homebrew method of OpenCV3 installation? I can’t seem to find it on the website.
Thanks for everything!
Adrian Rosebrock
Thanks for reminding me about this. I’ll try to get it online within the next month.
Hank
If anyone is interested, you can easily set the location of a conda virtual environment as your pyton library source, instead of using virtualenv.
Adrian Rosebrock
Thanks for sharing Hank.
mehul
hi this is the great guide , i have followed all the steps but finally when i run the code it hits me this error
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /Users/mehulmistry/opencv/modules/imgproc/src/color.cpp, line 7564
Traceback (most recent call last):
File “test.py”, line 6, in
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.error: /Users/mehulmistry/opencv/modules/imgproc/src/color.cpp:7564: error: (-215) scn == 3 || scn == 4 in function cvtColor
Adrian Rosebrock
Make sure you have downloaded the jurassic_world.jpg image and placed it in the same directory as your
test.py
. You are getting this error because thejurassic_world.jpg
image is not in the same directory as your Python script.mehul
thank you , for the quick reply
isaac vidas
Great tutorial! Thank you very much!
I had a few issues during the cmake step and the “make -j4” step. I don’t know if it’s because of changes in the installation or a different reason specific to my environment.
When I ran cmake I couldn’t get python2 to be in the list of modules to be built.
After taking a look in “opencv\CMakeLists.txt” I found out that some of the parameters were changed:
1) PYTHON2_LIBRARY – changed to PYTHON2_LIBRARIES. The value stayed the same.
2) PYTHON2_INCLUDE_DIR – was removed and not being used.
3) PYTHON2_NUMPY_INCLUDE_DIRS – was added and should be pointed to the include dir of numpy.
4) BUILD_opencv_python2 – In the CMakeLists.txt this parameter is used in the condition of building opencv for python2 so I used this as well.
I ended up with the following command:
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local \
-D PYTHON2_PACKAGES_PATH=~/.virtualenvs/cv/lib/python2.7/site-packages \
-D PYTHON2_LIBRARIES=/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework/Versions/2.7/bin \
-D PYTHON2_NUMPY_INCLUDE_DIRS=~/.virtualenvs/cv/lib/python2.7/site-packages/numpy/core/include \
-D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON \
-D BUILD_EXAMPLES=ON BUILD_opencv_python2=ON \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules ..
You also need to make sure that PYTHON2_NUMPY_INCLUDE_DIRS is correct. In my case, I didn’t set the PYTHON2_NUMPY_INCLUDE_DIRS value at first, so it used the default value “/.virtualenvs/cv/lib/python2.7/site-packages”. While the cmake step finished successfully, the “make -j4” failed with the following error: “fatal error: ‘numpy/ndarrayobject.h’ file not found”.
I fixed this error by pointing the PYTHON2_NUMPY_INCLUDE_DIRS parameter to the include library of numpy in the virtualenv. You can find “ndarrayobject.h” in this folder.
I’ve installed this on OS X Yosemite 10.10.4.
Hope this helps.
Adrian Rosebrock
Thanks so much for the tips Issac! Very interesting that the CMake options have already changed though.
isaac vidas
I think so too. It’s also weird that there’s so little documentation about it.
Adrian Rosebrock
Welcome to the world of OpenCV! But that’s too be expected. OpenCV 3 is barely a month old, whereas OpenCV 2.4 was the major version for years. It’s going to take awhile for good documentation on it to appear. I just hope that PyImageSearch can be one of those “good documentation” websites.
isaac vidas
I think PyImageSearch is already one of those websites.
I’ve been returning to this site for a while now and I really like what you’re doing with it.
I have some ideas that I wanted to try with OpenCV and when I wanted to get started, this was the first place I went to.
Thank you for all the great tutorials and examples!
Adrian Rosebrock
That’s really great to hear Issac! 😀
Moe
Thank you so much Isaac, you have saved me from a lot of headaches :)!
Jay Ludher
Hi! Sorry to bring back to life an old topic. I’m doing this new change as i also looked at the CMakeLists.txt file and saw the new headings. However, when i change to the new format and run cmake, i’m still having python 2 in my list of unavailable and my interpreter is pointing to /usr/local/bin/python2.7 (ver 2.7.11) instead of pointing to Users/Ludhercris/.virtualenvs/cv/bin/python2.7 …… any help?
Chris Alvino
Thanks for including this comment! It saved me a lot of time.
Trozdol
OMG! Thank you so much for posting this. I kept running cmake over and over thinking I had some typo. Driving me Crazy!
Pat1234
Thanks so much Isaac!
I have a problem regarding the “make -j4” step. I ran cmake and python2 is in the list of modules to be built.
When I run “make -j4” i get the reply “make: *** No targets specified and no makefile found. Stop.”
I am very new to this so its probably a beginners mistake.
Can anyone help me out?
Thanks!!
Adrian Rosebrock
If you’re getting an issue related to “No targets specified”, then it’s likely that your CMake command exited with errors. Double-check your output from CMake and you’ll likely see errors that need to be resolved.
Nic
What a lifesaver. Thanks for the clear example.
However, though it almost worked for me, I still had to set INSTALL_C_EXAMPLES=OFF
bhagyeshm
Oops!! I realised that I am asking for “which python” instead of asking “which python3”..Thanks anyways Adrian for the lovely book ‘Practical Python and OpenCV’! Everything is simply there at one place.
Adrian Rosebrock
Glad it’s working for you! And that’s awesome that you are enjoying the book! 😀
Alex
Thank you very much; this was well-needed!
Also thanks to Isaac Vidas, as I was having the same issue.
What would we do without these practical, yet passionate, tech blogs? When will proper documentation development receive the attention it deserves!? (not just for OpenCV)
Cheers,
Alex
Adrian Rosebrock
Thanks for the kind words Alex! 🙂
Xi Wang
Great tutorial! I followed exactly the same steps and got exactly the same results on my MacBook Air. Thank you so much for the accuracy!
Adrian Rosebrock
Awesome, glad to hear it! 😀
Reza Kalantar
Thanks for sharing, I keep getting the error: make: *** [all] Error 2 at around 38% and have followed exactly the same steps. I would appreciate if you can help me with this. Many thanks
Adrian Rosebrock
What is the exact error message you are getting? Without knowing the error I cannot provide any suggestions on how to resolve it.
Mike
I ran into a problem where, after running make -j4, I got an error saying Python.h was not found.
The problem was that when I ran cmake, I used this option:
-D PYTHON2_INCLUDE_DIR=/usr/local/Frameworks/Python.framework/Headers
That file was an alias to a folder that didn’t exist, for some reason. I just changed it to:
-D PYTHON2_INCLUDE_DIR=/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework/Headers
and it worked.
Adrian Rosebrock
Awesome, thanks for the comment Mike!
Dan
Hi Mike/Adrian, sorry to bring up an old topic, but I have tried both of those paths that you have suggested and I still keep getting a fatal error around 78% because Python.h cannot be found.
My Python.h file exists in System/Library/Frameworks/Python.frameworks/Headers.
Any suggestions on why this might not be working? I’ve run the Cmake command again a few times trying those paths out but nothing seems to be working. Thanks for your help!
Adrian Rosebrock
Which version of Python are you using? And which version of the Mac OS?
Kusuma Ramesh
Hi
I am trying to install openCV3.0 and Python2.7 on OSX. After installing python from the brew, making necessary changes for .~bash_profile file and type $ which python on the terminal.It is showing the system version of python and not the python installed from brew.Please help
Adrian Rosebrock
After updating your
.bash_profile
file did you reload it using:$ source ~/.bash_profile
Alternatively, you could launch a new shell and try
which python
If it is still showing the system version of Python, then it’s likely that your
.bash_profile
file was not updated correctly.cesar
when i use:
git clone https://github.com/Itseez/opencv.git
i get:
Illegal instruction: 4
im using mac 10.7.5
can u help me, please?
Adrian Rosebrock
That sounds like an issue unrelated to OpenCV, but with git and your OSX install. I’m not quite sure why you would be getting that error (other than OSX 10.7 is pretty dated at this point). You can read more about it here, but again, the issue is most certainly with your git install, not OpenCV.
Chris
Hi Adrian, I just want to install OpenCV 3.0 on Mac to use with C++. I followed your instruction, but from Step 6 I exited the cv virtual environment and installed the rest globally, because I was afraid that it won’t work with XCode (or any other C++ IDE) if I keep installing under the virtual environment. In the end I coudn’t find the cv2.so anywhere (either in site-packages or build/lib). I haven’t tested with C++ (Xcode) yet but just wanted to ask you if what I did could lead to any potential problem? Overall, how do I get it to work with both Python and C++? Thanks
Adrian Rosebrock
Hey Chris, I’ll be honest — I don’t do much C++ development, and when I do, it’s on Ubuntu, not OSX so I’m not sure I’m the best person to answer this question. But to answer your question, you should still follow the the same install instructions I have provided. The
sudo make install
command will install OpenCV globally on your machine. The only extra step is to sym-link thecv2.so
file into your virtual environment. Other than that, you should be able to run Python scripts and compile C++ programs.Chris
Cool so this time I followed the exact instruction and I was able to build OpenCV 3.0 for both Python and C++ (Xcode). Thanks a ton. Even though I don’t use Python, I’ll follow your blog to learn more about features in OpenCV (rather than looking into OpenCV documentation).
Two quick questions though as I’m pretty new to python: (1) How to reactivate the cv virtualenv once I close the current terminal and start a new one? ; (2) Once your test_akaze.py is running from terminal, how do I close it? I tried a couple options (ESC, q, exit(), etc) but the only one that stops it is Ctrl + z, but then the python session is still running and in order to close the image window I have to force close it. Is there a better way? Thanks
Adrian Rosebrock
1. Use the
workon
command to access thecv
virtual environment:$ workon cv
And that will drop you back into the
cv
environment2. Click on the window first, then press any key — this will close the window.
Chris
Thanks Adrian, all work very well.
Noel García
Thanks a lot!
Mark
Hello Chris. Can you tell me what did you do exactly? I already can use Python+OpenCV to build programs, but It’s not very clear how to build with C++ and Xcode. Thanks.
Floren
I followed these instructions to configure Xcode.
https://www.youtube.com/watch?v=XJeP1juuHHY
and my C++ test script worked.
bill
After wiping an old home-brew install and resetting all the foobared permissions, I am getting the following error wen attempting to make opencv:
[ 79%] Linking CXX executable ../../bin/cpp-tutorial-pnp_registration
[ 79%] Built target cpp-tutorial-pnp_registration
[ 79%] Linking CXX executable ../../bin/opencv_perf_stitching
[ 79%] Built target opencv_perf_stitching
make: *** [all] Error 2
What is going on and how to fix it?
cmake complains about PythonLibs2.7, but doesn’t see the libpython1.7.10 in the Cellar.
make notes that “libopencv_hal.a” has no symbols.
Thanks
oops: that is lib python2.7.10 in the cellar
Thanks Hackeron,
I also had the Python.h problem. Fixed it as suggested above and everything compiled and installed.
never mind. It was the Python.h problem. fixed that and everything worked.
Scott Squires
Tried to install twice now.
Same issues each time.
-D PYTHON2_LIBRARY=/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework/Versions/2.7/bin \
I had to change to python/2.7.10_2 since that was the folder created for some reason.
Any of the make files on cv fail errors in the video codecs. Complains about x86, etc.
In the end import cv2 doesn’t work since it can’t find cv2
Suggestions?
Adrian Rosebrock
If you are getting compile errors, then yes, OpenCV will not be able to finish compiling and install. The library must be compiled correctly and installed correctly before it can be imported.
Try changing your
PYTHON_LIBRARY
to point to the.dylib
file so it can be linked against. The path on your machine will likely be different, but for me it's:-D PYTHON2_LIBRARY=/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/libpython2.7.dylib
kota
Thanks Adrian. Previously I used the following but didn’t work (everything worked but import cv2)
PYTHON2_LIBRARY=/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework/Versions/2.7/bin
Then I changed it to .dylib and it worked now.
Since I couldn’t find satisfying answer about what .dylib does, can you shed some light about why it works now?
Adrian Rosebrock
A dylib file is a dynamic library that’s loaded at runtime rather than compile time (hence why your error only happened during the import). If you’ve ever done any Windows or DOS programming, dylibs are essentially parallel to DLL files.
Kuan
Just wanted to chime in and say thanks for the very helpful tut.
Adrian Rosebrock
Thanks Kuan! 🙂
Bernd Meyer
Despite Adrian’s generous help I couldn’t quite get this to work in my environment, but based on this and another blog I finally found the solution. If you, like me, are tortured by the “‘unsupported/Eigen/MatrixFunctions’ file not found” bug, this solution may also work for you: http://wp.me/P3ALAE-82
Adrian Rosebrock
Thanks for sharing Bernd, I’m glad OpenCV is now installed for you 🙂
Nick
Hi Adrian, I followed your instruction twice and checked every step, but I still could not get the modules from opencv_contrib. I tried with SIFT by running sift = cv2.SIFT() and I got this error: AttributeError: ‘module’ object has no attribute ‘SIFT’ (import cv2 works fine btw). I check in /usr/local/include/opencv2 and there’s no folder nonfree which suppose to include the header for SIFT and SURF etc. Can you help? Is there any screen output in the process that we can check if opencv_contrib is added. I did have the line “-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules ..” in the cmake command. Thanks
Adrian Rosebrock
Hey Nick, you might want to give my post on “Where did SIFT and SURF go in OpenCV 3?” a read. SIFT and SURF have both moved to the
xfeatures2d
sub-module so you can actually access them via:cv2.xfeatures2d.SIFT_create()
Nick
Oh, thanks, should have asked you earlier. Appreciate it 🙂
Adrian Rosebrock
No problem Nick 🙂
SPQR
brew doctor now complains with :
Unexpected dylibs:
/usr/local/lib/libopencv_adas.3.0.0.dylib
/usr/local/lib/libopencv_bgsegm.3.0.0.dylib
…
/usr/local/lib/libopencv_xobjdetect.3.0.0.dylib
/usr/local/lib/libopencv_xphoto.3.0.0.dylib
Adrian Rosebrock
Did you install OpenCV via brew or from the source like detailed in this post? I haven’t ran into a problem with brew doctor when compiling from source.
Ashwin
I wanted know if I will be able to change the number of dedicated cores for OpenCV.
Say, I’ve already complied OpenCV and mentioned “make -j4”. But now, I want to change it to 2 cores. How do I do it?
Adrian Rosebrock
Hey Ashwin — I think there might be a bit of confusion. The
-j
option controls the number of cores that is used compile OpenCV, not the number of cores that OpenCV will use once compiled, installed, and performing various operations. OpenCV determines that automatically and can be further improved by compiling with TBB support.Sarath
Hi,
I tried to install opencv for python2.7. i end up with the error Python.h not found.
i checked my PYTHON_INCLUDE_ DIR path, for me it is /Library/Frameworks/Python.framework/Headers . I checked the directory, i have Python.h file is present inside it.
i also have Header directory in /Library/Frameworks/Python.frameworks/Versions/2.7/Headers. which one should i choose.
Is there any way to find the correct path?
I did not install python using brew. does it matters? if, How could i remove preexisting python and install using brew.
Please help me..
Adrian Rosebrock
Yes, it does matter if you did not install Python via brew. If you do not install Python via brew, you will end up compiling against the OSX version of Python. That’s not necessarily a bad thing, but you’ll need to change your paths accordingly. You do not need to uninstall the system version of Python to install another version — just let brew take care of it for you like I have outlined in this blog post.
Me
I followed all the steps and Igor it to work. The next time I restarted the computer I used ‘workon cv’ to switch to the virtual env, but the example code stopped working. A little digging in with ‘pip list’ showed that I lost the packages…
Any idea how to get the packages to persist between restarts?
Adrian Rosebrock
It sounds like you need to re-access your virtual environment:
Make sure you are always in the
cv
virtual environment before executing your Python script.justin ng
Hi Adrian,
I have installed OpenCV 3.0.0 on Ubuntu but somehow when using python and check “cv2.__version__”, it still returns “2.4.8”.
Thus, I can not use some xfeature2d functions.
Could you suggest any ideas to get my python work with OpenCV 3.0.0
Adrian Rosebrock
That’s quite strange. Have you previously installed OpenCV 2.4.8 on your system? If so, make sure you are in the
cv
virtual environment so you are seeing the OpenCV 3.0.0 bindings.Vic
I attempted to create the virtual environment by:
mkvirtualenv cv,
but i got:
-bash: mkvirtualenv: command not found
Adrian Rosebrock
I would go back to Step 3 and make sure your
~/.bash_profile
file is properly edited. Then, make sure to reload it viasource ~/.bash_profile
Felicia Amy
Hi,
I also have problem with this. Somehow the virtualenvwrapper.sh is stored here “/Library/Frameworks/Python.framework/Versions/2.7/bin/” instead of “/usr/local/bin/”. Do you have any idea what went wrong in my case? Thank you.
hendrick
same problem with me. I already make sure my ~/.bash_profile. but when I run which python the result is usr/bin/python
Adrian Rosebrock
Which version of Python and pip did you use to install virtualenv and virtualenvwrapper?
Pawan Ajagond
Use this line of code :
source /usr/local/bin/virtualenvwrapper.sh
and then this line of code:workon cv
Peter
Hey Adrian,
first I have to thank you for this amazing manual. Everything works fine right now and it was fun to get some background information as well.
After the install process there are two folders in the home directory: ~/opencv and ~/opencv_contrib.
Are they necessary after installing? Can I delete them or what should I do with them?
Thanks and all the best from Germany
Peter
Adrian Rosebrock
Nice, I’m glad the tutorial worked for you Peter! 😀
After you run
make install
you can safely deleteopencv
andopencv_contrib
.Peter
Hey Adrain,
after the install process there are two folders in the home directory. opencv and opencv_contrib.
Are they necessary or can I delete them?
Best and thanks for the helpful manual.
Peter
Adrian Rosebrock
Yep! After you’ve ran
make install
you can safely delete theopencv
andopencv_contrib
directories.Pai
Super!
I’m able to install after following instruction given.
Thanks,
Pai
Adrian Rosebrock
Great, I’m happy the install instructions worked for you Pai! 🙂
Mike Mehr
Hi Adrian,
I got this all working after I realized that my initial error (C compiler cannot create executables) in Cmake had to do with not having the Xcode Command Line tools (I had to look that one up on Google/StackOverflow). Everything else proceeded just fine, including the final test run. Except for not knowing how to quit out from the running Python script (lots to learn about Python!).
Can I now run the install for Python3 as well? Should I? I’ll see if there are comments on that page about that issue.
Anyway, thanks for setting all this up and I’m looking forward to learning more with you.
— Mike
Hi Adrian,
I did do this page after doing the 2.7 install page; the brew install python3 got me v3.5.0, so I modified the CMAKE command accordingly, but after the make build, I could not find the cv2.so file anywhere, not in the path specified by Rick, nor the 3.5 path as you suggested. The old 2.7 package in the cv virtualenv is still there and still works under 2.7. I assume if it had put the 3.5-compiled .so file there, it would NOT run under 2.7, so I’m at a loss to explain where it might have gone. Any suggestions? I noted some differences in the output of CMAKE around the Python stuff, but the 3.5 stuff was called out properly.
Best,
Mike M
Further update (fixed the problem). I am not sure what step(s) below exactly fixed the problem above, but among the things I did were:
1. Made sure there was only one set of virtualwrapper.sh calls in my .bash_profile
2. Renamed /usr/local/bin/python2.7 temporarily so the old interpreter couldn’t be found by CMAKE
3. Reran the CMAKE line, which then only found the 3.5 interpreter.
4. Reran make -j4 so that it was built with Python 3.5
5. Put the /usr/local/bin/python2.7 link back
6. Found the .so file at ~/opencv/build/lib/python3/cv2.cpython-35m-darwin.so and copied it to ~/.virtualenvs/cv3/lib/python3.5/site-packages
7. Opened python3 and verified that import cv2 worked.
My clue was noticing that when it wasn’t working, the make didn’t actually link the .so file in the final step, only building the video-write tutorial. I became suspicious of the line of CMAKE output “– Python (for build): /usr/local/bin/python2.7” and thus my steps #2-4. Only took 2 hours extra! Is this a bug in the build script?
Regards,
Mike
Adrian Rosebrock
Hey Mike — congrats on getting OpenCV installed! And thanks for following up with all the added details (I’ve consolidated all your comments into a single one just for ease of readability). I’m sure other PyImageSearch readers will find your comment helpful.
As you noted, there should only be one set of virtualenv and virtualenvwrapper calls in your
.bash_profile
. Both of these packages are compatible with Python 2.7 and Python 3. It’s also strange that you needed to manually movepython2.7
. Provided the library and interpreter flags were set to point to Python 3.5, this should not have happened. But then again, each OSX system is a bit different.As far the strange
cv2.so
, there must be a bug in the build script. It only happens for Python 3, not Python 2.7 which is quite odd.gyurisc
Thanks for posting this. It is very useful. I could not do the installation without your guide.. 🙂
Adrian Rosebrock
No problem!
James
Hi Adrian
Thanks for the great tutorial!
I’m currently doing step 10 and restarted the terminal (for no particular reason), however I get this error:
What’s the best way around this?
Best wishes
James
Adrian Rosebrock
Hey James, if you ever open up a new terminal you need to use the
workon
command to re-access yourcv
virtual environment:$ workon cv
This will drop you back down into the Python virtual environment and you’ll be able to successfully import the OpenCV library.
James
Hey Adrian, thanks for your help and quick reply. Everything is working as it should now!
Adrian Rosebrock
Fantastic, glad to hear it James!
Daniele
Hi Adrian, thanks for the great guide! I installed it without virtualenv by skipping the virtualenv part and using PYTHON2_PACKAGES_PATH=/usr/local/lib/python2.7/site-packages
It worked without any problem on El Capitan 10.11.1, Really thanks for all your work!
Adrian Rosebrock
Nice, I’m glad it worked for you Daniele!
David Kadouch
As always this is wonderful tutorial for your winning series of tutorials. One comment is that in the cmake command the PYTHON2_LIBRARY and PYTHON2_INCLUDE_DIR paths for python2 in cmake didn’t work for me, leading to errors during the build process (make -j4). I have python2.11 and not 2.10 as in your example. I found that you can modify the command by pointing everything to the virtual env. This way it’s less dependent on how your physical env is configured in reality. Here’s the modified command:
HTH
David
Adrian Rosebrock
Thanks for passing along the updated command David!
Luca
Thanks so much David! This was killing me for the longest time…
Piyush Santwani
Thank you David Sir.
Tsang-Kai
This one works for me! Thank you so much, David.
Hilman
Hey, great tutorial. Just want to ask something. Sorry if it sounds fool because I am a beginner (with spirit to master image processing!).
1. I am using El Capitan and follow all of your instructions. Is it ok?
2. Why need to install python when in fact the os x come with installed python?
Adrian Rosebrock
Yes, you can certainly use El Capitan. And the reason you install a separate Python version is so you don’t break the systme install one if anything goes wrong.
Hilman
I think I’ve done it. I just copied the cv2.so in the build.lib to the site-packages. Is it ok?
Adrian Rosebrock
Yes, that is perfectly okay.
Hilman
Hey Adrian, I have another question.
Every time I want to use the opencv 3 with the python for my work, through the terminal, I must run the “mkvirtualenv cv” command first?
Adrian Rosebrock
You only need to run
mkvirtualenv cv
once. After that, you just need to runworkon cv
to access thecv
virtual environment. You can read more about Python virtual environments here.Hilman
I’ve read it. Great article by the way :).
Just to make sure:
1. If I corectly follow the above steps during installing python 2.7+ And opencv 3, I just need to type in “workon cv” and no need to type other command like “source virt1/bin/activate” etc.
2. Before this I’ve already entered “mkvirtualenv cv” like many times to enter the cv environment as I didn’t know the method above. Will it affects anything?
Adrian Rosebrock
1. Correct, once you’ve already gone through the installation steps you just need to use the
workon cv
command — that’s all that is required to drop you down into thecv
virtual environment.2. This shouldn’t affect anything. The
mkvirtualenv
command is “smart” enough to know that the virtual environment already exists and won’t overwrite anything.Adolfo
Hi. Thanks very much for the tutorial!
I did everything and it’s working but it seems that the SVM module is not included. Anyone else has that problem?
Robert Joseph
Adrian, thank you so much for your walkthrough! I need libopencv_contrib.dylib to be built but when I follow your steps (for both opencv and opencv_contrib) I see cmake output reports that contrib is not being built. gist: https://goo.gl/ENWUNA
Does this make any sense to you? Am I missing something obvious? Any help would be MUCH appreciated!
Adrian Rosebrock
Hey Robert, thanks for using a gist, that really helps improve the readability of the output (and ensure the comment isn’t accidentally marked as spam).
Your output of CMake is actually correct. Modules such as
xfeatures2d
,ximgproc
, etc. are part of theopencv-contrib
package. You can safely go ahead and compile OpenCV and the additional contrib package will be installed.The
world
andcontrib_world
are the old (unneeded) OpenCV bindings.Bangor
Thanks for the article, I’d have taken years to figure this out on my own!
Random question from a complete amateur who decided to get ambitious: Any idea why CMake would fail with:
CMake Error at samples/gpu/CMakeLists.txt:100 (list):
list sub-command REMOVE_ITEM requires list to be present.
When checking out the just released OpenCV 3.1.0?
Following the instructions and checking out 3.0.0 instead works perfectly, so I’ll be using that!
🙂
Adrian Rosebrock
I personally have not tried to compile OpenCV 3.1 yet, so I’m not sure about this error message. I will look into it.
shomz
Hi, Adrian! I was wondering what steps should be skipped and what should be changed to install without the virtual environment. I tried to install with it, but I am a beginner and probably made a mistake along the way, because it did not work in the end. I plan to use PyCharm, is that ok? Thank you!
Adrian Rosebrock
You can certainly use PyCharm with OpenCV. Please see this post for more information, although it does assume you are using a Python virtual environment.
As for the steps required to not use the virtual environment, simply skip the installation of
virtualenv
andvirtualenvwrapper
along with themkvirtualenv
andworkon
commands.Sanjay
After struggling through old documentation on OpenCV this is a breather with new and updated versions. Thank you!!
Adrian Rosebrock
Awesome, I’m glad the instructions worked for you Sanjay! 🙂
Jackson Isaac
Hi,
Nice tutorial. With 3.1.0 version there is an issue in
samples/gpu/CMakeLists.txt line 100
.Hence while building 3.1.0 version I had to drop
-D INSTALL_C_EXAMPLES=ON
. Didn’t try any other workaround though.Adrian Rosebrock
Thanks for the tip Jackson! I have confirmed this issue as well.
Rohan
I couldn’t install it the first time around.
After removing all of the brew and pip installations from their respective directories, I removed python 2.7.
I re-installed with brew and made sure ‘brew doctor’ didn’t show any errors.
Then, the installation worked properly.
Adrian Rosebrock
Thanks for sharing your experience Rohan!
Moe
Hey Adrian, thank you so much for this great tutorial.
Two questions:
First, in step 9, how do I get the (cv) before your computer name in the terminal? Is it necessary to always run “mkvirtualenv cv”? Also, am I understanding correctly that the (cv) is called the virtual environment?
Second, in the very last step while testing. How do I terminate/exit the process after running “test_akaze.py” properly? Pressing ctrl-C does not work as it simply prints “^C” in the terminal, also the Python output has no exit button. Should I simply quit the Python window with cmd+Q?
Thank you once again for what you do!
Adrian Rosebrock
Hey Moe, to answer your questions:
1. The
mkvirtualenv
command only needs to be run once. After that, you just need to runworkon cv
to drop into thecv
virtual environment.2. Click on the window and press any key. This will exit the Python script.
Moe
Thanks for the reply, Adrian.
If I ran “mkvirtualenv cv” multiple times, what are the consequences? Does it just rebuild or does it create multiple environments? I’m asking because I ran it a second time before your reply.
Thanks :)!
Adrian Rosebrock
Running
mkvirtualenv cv
multiple times won’t hurt anything — it’s smart enough to realize that the virtual environment already exists and will not overwrite it. It just drops you down into the environment.Vihbor
file cv2.so doesn’t exit..what to do?
Adrian Rosebrock
There are many reasons why the
cv2.so
file might not show up. I would suggest taking a look at the Troubleshooting section of this post.mandysmoak
I am having the same issue. Unfortunately, I found no solutions on the suggested Troubleshooting section.
Any other suggestions??
Adrian Rosebrock
As mentioned in the “Troubleshooting” section, it’s really hard to diagnose why OpenCV may fail to import. The best suggestions are to (1) ensure you are in the
cv
virtual environment prior to trying to import OpenCV and (2) ensure that OpenCV compiled without any errors.mandysmoak
Found my problem! I didn’t notice that python2 was in the Unavailable section, rather than the Opencv after the cmake command. I used the one provided by isaac above and everything works!
Thank you so much for this tutorial!
Adrian Rosebrock
Congrats on resolving the issue!
aaz15
Hello Adrian,
I just crossed your blog and its packed with excellent resources. Thank you for your guide.
While testing, I came accross this error
AttributeError: 'module' object has no attribute 'AKAZE_create'
any ideas why?
Adrian Rosebrock
Which version of OpenCV are you using? It works under v3.0.0.
isunchy
I came across the same error.
What should I test opencv under OpenCV v3.1.0?
versionHell
Hi. I also had this error. I was able to successfully run the sample after doing the following:
1. I had originally built 3.1.0, so I then built 3.0.0
1a. I have python 2.7.11, so I had to change this line:
PYTHON2_LIBRARY=/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/bin
2. It still wasn’t working, but I determined it was because I was running python outside of the virtual environment (my desktop), which is linked to openCV 2.4 instead of 3
3. copying the sample code and image to the .virtualenvs/cv/lib/python2.7 folder, then running it from there worked as expected
Adrian Rosebrock
Once you have successfully created the virtual environment, you do not need to put code directly in the
.virtualenvs/cv/lib/python2.7
folder. Instead, just use theworkon
command to access the virtual environment and then execute your Python script:Nate
Thank you for this.
Adrian Rosebrock
I’m glad it worked for you Nate! 🙂
Jiezhi
Great!
It helps me a lot!
Adrian Rosebrock
I’m glad to hear it Jiezhi! 🙂
Rahul
thank you for the wonderful setup instructions..
Adrian Rosebrock
No problem, I’m happy the install instructions worked for you Rahul!
Gani Siva Kumar
Thank you,I had successfully installed opencv. How can I add scipy now to virtualenv to work in opencv?
I installed scipy through “pip install scipy”.But it showing import error while working in virtualenv.
Adrian Rosebrock
You need to access the
cv
virtual environment and then use pip to install it:Gani Siva Kumar
Thanks Adrian! It worked =D
Niko
I just installed a fresh copy of the newest el capitan version.
Im using python version 2.7.11 and OpenCV Version 3.1.0. And yes i set “INSTALL_C_EXAMPLES=OFF -D” so CMake was able to compile without any errors.
I followed the tutorial till step 9 i had no issues. But i can´t find the “cv2.so” file, the openCV bindings in my “~/.virtualenvs/cv/lib/python2.7/site-packages/” directory. I´ve been using “workon cv” . Of course i cant sym-link cv2.so and python error : “ImportError: No module named cv2”. The troubleshooting post from https://pyimagesearch.com/2015/10/26/how-to-install-opencv-3-on-raspbian-jessie/ doesn´t solve the problem.
Which is the best workaround for now ?
I don´t know why cv2.so was not created.
Greeds Niko
Adrian Rosebrock
Can you confirm that the
make
command successfully compiled OpenCV? If so, check yourbuild/lib
directory after the compile. Thecv2.so
file should be in there. Once you find it, you can move it/sym-link it into the virtual environment.at0mb0y
Hi, as some other I have trouble to install openCV. I’ll not bug the comment with my bash output but can you be clearer at the step 6. Should we brew install while we are in the virtualenv cv ? or outside ? it’s not clearly explain we we are in or out.
Thanks for your post
Adrian Rosebrock
The
brew
package should have been installed way back in Step 2, long before you installvirtualenv
. Once you’ve installedbrew
, you then proceed with the tutorial.at0mb0y
Sorry that’s not what I mean.
At the step 6 we are in the virtual env or out ?
should we type at sometimes “deactivate” to get out of virtualenv before step 6 ?
Adrian Rosebrock
No, do not leave the virtual environment. It is important that you stay inside the virtual environment so that the CMake commands picks up the correct Python version.
Lirone
Thank you !
So just to be sure, If I already have in my laptop OpenCV 2.4, It won’t be overwritted right ? I can use both on my computer without problem (meaning without create any conflict ?)
Adrian Rosebrock
Technically yes, but sometimes there are gremlins in the system. I normally only run
sudo make install
for one of the installations, from there I run a compile for each OpenCV + Python version and then delete everything but thecode/build
directory. I then create a virtual environment that points to each respective version.Lirone
Thank you Adrian for your answer.
I made a silly mistake. In the step 8 PYTHON2_LIBRARY=/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework
I didn’t notice that I have python 2.7.11 installed, therefore it didn’t work when I wanted to import cv2.
I replaced 2.7.10 with 2.7.11, re make, and it worked. 🙂
Adrian Rosebrock
Congrats on resolving the issue Lirone 🙂
Zakai
I’m not sure if my first question is going to post or not, but I have resolved it. Now I am having another problem where after the build has compiled and I go to install it the cv2.so file isnt located in my site-packages directory. It shows up in my opencv/build directory, so I believe the install goes correctly but is not linking with the cv virtualenv and python.
Adrian Rosebrock
Hey Zakai — I’ll look into the spam filter to see if your first comment got caught there. In any case, you should check the
dist-packages
directory as well. Finally, if it’s still not there, then manually copy thecv2.so
file frombuild
into thesite-packages
directory of your virtual environment.Akhila
Hello!
Thank you for the great tutorial! I am interested in using openCV 3.1.0, specifically the DNN module that is in opencv_contrib. I followed your tutorial and was able to install 3.1.0. I know the contributions were installed because “cv2.xfeatures2d.SIFT_create()” works. However, the module “cv2.dnn” does not exist. Do you have any thoughts on how I can use it?
Thanks!
Akhila
Adrian Rosebrock
I personally haven’t used the DNN sub-module of OpenCV yet. My understanding is that the DNN module is a placeholder to load and run pre-trained Caffe or Torch networks. It’s not actually used to currently train a network. I also don’t think this module is exposed to the Python bindings (yet).
Vijay Kamarshi
Hi Adrian,
Not sure what I did, but I deleted the terminal instance, launched a new instance, did “workon cv” and reran cmake (with python includes and libraries pointing to the virtualenvs environment as suggested by some helpful person above). And cmake was able to configure correctly this time. Not sure why it failed first time around. By the way, for people not so familiar with cmake, I fount it best to delete the build directory and create a fresh one everytime you make a new cmake attempt. Just my 2c to add to the “folklore”.
Regards,
Vijay
Adrian Rosebrock
Thanks for the input Vijay, it’s much appreciated! 🙂
Jose Sotelo
Hello. Im following your tutorial and everything was perfect until Step 10. Im pretty new into phyton, OpenCv and programming at all, so I cant create a new file…. It must to be inside Xcode, the terminal or in a text file? Im lost :(((
Thank you for any help
Adrian Rosebrock
You can create the sample Python script in whatever text editor you would like. That could be XCode, Sublime Text, nano, vim, emacs, TextEdit, etc. Once you have created the Python script, open up your Terminal and execute the script.
Rob
Thank you for this tutorial!
In case it helps anyone:
In my case “make -j2” (I have a dual core MBP) failed with “fatal error: ‘hdf5.h’ file not found”. In cmake, I noticed that it was searching /Users/rob/anaconda/… (my previous Python installation used Anaconda) for HDF5.
Even though my .bash_profile had the right path and I ran source, I noticed that cmake was still finding an old version of HDF in the anaconda directory.
I did two things at once so I’m not sure which fixed it:
First, I updated Anaconda by running “conda update conda” and it turns out my Anaconda installation (and probably HDF) were a year out of date. Then, even though “which python” was returning the Homebrew installation, I completely removed the anaconda path in .bash_profile, rand source again, and created a new virtual environment.
I recompiled and there were no errors.
Adrian Rosebrock
Thanks for sharing your experience Rob, that’s super helpful!
Ernie
Interesting — I’m having the same issue, yet I don’t have Anaconda installed 🙁
No idea how to fix it.
Sujit Pal
Six months too late for Ernie, but maybe someone else has this problem and stumbles upon this comment…
I was trying to install OpenCV 3.1.0 with Anaconda Python 2.7.12 using Adrian’s guide. For the cmake, I skipped setting the PYTHO2_* variables hoping they will get set to the Anaconda defaults. During “make -j4”, I had the same problem with the missing hdf5.h that is mentioned in the thread above.
I was ultimately able to fix it with the hack proposed by @avtomatons in OpenCV Issues #6016 (and replicated in #6050), ie, adding the following lines to the OPENCV_HOME/modules/python/common.cmake.
find_package(HDF5)
include_directories(${HDF5_INCLUDE_DIRS})
Also, many thanks to Adrian for writing this awesome how-to for installing OpenCV 3.x on Python (with SURF and SIFT). Just verified that I can create a SURF object in my REPL like so:
>>> import cv2
>>> surf = cv2.xfeatures2d.SIFT_create()
>>> surf
Adrian Rosebrock
Thanks for sharing Sujit!
Anton
Hi Adrian,
Thanks so much for this – this was tremendously helpful. I was able to successfully carry out the OpenCV 3.1.0 installation on my Mac, but I’m having a problem as I now need to find cv2 equivalents to certain (older) cv functions and I’m struggling mightily to figure out what they might be. In particular, I’m looking for cv2 equivalents for:
cv.FindStereoCorrespondenceGC()
cv.GetReal2D()
cv.CreateStereoGCState()
I’m looking for these too, but they’re less important:
cv.Set2D()
cv.LoadImage() (here I can probably use imread())
cv.CreateMat()
cv.ConvertScale()
More concretely, what I’m trying to do is create a disparity map using the Graph Cuts (GC) implementation. Has this functionality been stripped from OpenCV 3? If so, is there any way to access the older functions?
I’m willing to try the C++ route (as opposed to Python), if need be.
Thanks very much for your help!
Adrian Rosebrock
Hey Anton, thank sfor the comment. To be honest with you, I do very little work with stereo vision, so I’m not sure about your first set of functions, but I’m pretty sure this is a resource that would help out.
As for
cv.Set2D
, images are represented as NumPy arrays in OpenCV 2.4 and OpenCV 3. This means that we simply using NumPy indexing to access and set a pixel value:image[y, x] = (255, 255, 255)
The
cv.CreateMat
function is also not needed since we can use NumPy to allocate memory for an image:image = np.zeros((height, width), dtype="uint8")
Finally, the
cv.ConvertScale
function is not known ascv2.convertScaleAbs
.I hope that helps! And if you decide you want to learn more about the basics of OpenCV 2.4/3+ along with Python, be sure to take a look at Practical Python and OpenCV , which will help get you up to speed quickly.
Anton
Hi Adrian,
Thanks a bunch for your reply and tips. I was actually able to find and compile a pure C++ implementation of Graph Cuts which approximates the functionality of cv.FindStereoCorrespondenceGC(), so my problem is solved! The implementation is here, thanks to a French CV scholar called Pascal Monasse:
http://www.ipol.im/pub/art/2014/97/
The results are frankly tremendous (and a demo is provided.) Again, the power of Open Source shines through 😉
Again, thanks for your great site!
Adrian Rosebrock
Very nice, thanks for sharing Anton!
Cehasli
Thank you for sharing, Adrian. This article help me a lot 🙂
Adrian Rosebrock
Happy I could help! 🙂
mrfksiv
Thanks for this extremely concise tutorial! The AKAZE example works perfectly? But what is this anyway?:p
Adrian Rosebrock
AKAZE is a type of keypoint and local invariant descriptor. We often use it to describe the contents of an image. A great application is recognizing the covers of book, which I cover inside Practical Python and OpenCV.
Ade
Thanks Adrian for the excellent writeup.
For those struggling with getting Python 3.5 to work with OpenCV 3, I was able to make it work by changing the cmake parameters a bit:
http://peekay.org/2016/03/24/opencv-osx-python-3-bindings/
Adrian Rosebrock
Thanks for sharing Ade! 🙂
David Sterling
Thanks for the fantastic write-up Adrian — I followed your instruction but built OpenCV 3.1.0 on a fresh install of El Capitan 10.11. Everything went smoothly and Python bindings seem to work so far.
For anyone interested in the Matlab bindings the openCV 3.1 “contrib” installation doesn’t seem to be quite ready for prime time. The matlab compiler/code generator is only compiling *some* of the cpp files needed to implement the matlab bindings. Specifically line #30 in compile.cmake located in opencv_contrib/modules/matlab
file(GLOB SOURCE_FILES “${CMAKE_CURRENT_BINARY_DIR}/src/*.cpp”)
should be something like:
file(GLOB SOURCE_FILES “${CMAKE_CURRENT_BINARY_DIR}/src/*.cpp” “${CMAKE_CURRENT_BINARY_DIR}/src/private/*.cpp”)
so that the cpp files in build/modules/matlab/src/private are also compiled. Without these “Bridge” files some of the matlab bindings still work, but others (e.g. VideoCapture) produce errors about undefined “Bridge” functions) like this:
>> camera = cv.VideoCapture();
Undefined function or variable ‘VideoCaptureBridge’.
Error in cv/VideoCapture (line 15)
this.ptr_ = VideoCaptureBridge(‘new’, varargin{:});
A second issues with opencv_contrib/modules/matlab is that the compiler settings for Xcode 7.2.1
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin14.5.0
Thread model: posix
aren’t quite right as there is an issue with c++11 standards and resulting collision between cmath and math.h that causes some of the cpp files in the source/private to throw compiler errors. Maybe this is why they weren’t included in the first place??
Adrian Rosebrock
Thanks for the detailed comment David! I’m not much of a MATLAB users, but I know other PyImageSearch readers are and this comment is super helpful.
Matt Lashinsky
Awesome, got it to work!! Dude, you’re such a great teacher.
I had some issues setting up the build and ran into issues during compilation, but that’s because I installed openCV in a different directory rather than the home directory. So it’s important to be really diligent about specifying those paths to make sure they’re accurate.
Thanks Adrian.
Adrian Rosebrock
Thanks for the kind words Matt, I’m happy the tutorial was able to help!
João Crav
How can I open the ~/.bash_profile? very noob here
Adrian Rosebrock
You can open the
~/.bash_profile
file using your favorite text editor. If you’re just getting used to using the command line, then I highly recommend using nano:$ nano ~/.bash_profile
Michiel
I have the same problem as above, I use Sublime text 2, after which i type the ‘$ nano ~/.bash_profile’ tag at the line which i find by unhiding the console. I’m very new to this, any idea where I am going wrong?
Adrian Rosebrock
Hey Michiel — you should be typing
nano ~/.bash_profile
into your terminal, not Sublime Text.If you are very new to computer vision, OpenCV, and the terminal, I would suggest working through my book, Practical Python and OpenCV which will teach you the basics.
Furthermore, the Quickstart Bundle and Hardcopy Bundle of Practical Python and OpenCV include a pre-configured Ubuntu VirtualBox virtual machine with OpenCV pre-installed. This will allow you to skip the installation step and start learning immediately. Be sure to take a look!
cc
Thank you for this nice tutorial. I use OSX 10.10. A little bit of feedback:
1. ffmpeg is also needed. (easy installation by brew)
2. I got some errors and linking errors when I didn’t set
-D CMAKE_OSX_SYSROOT=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk -D WITH_QUICKTIME=OFF -D BUILD_opencv_hdf=OFF
, as a reference for people who can’t successfully install opencv by following this tutorial.
Adrian Rosebrock
Interesting, I personally haven’t ran into an issue where FFMPEG was required. Were you getting an error message at install related to FFMPEG?
Hilman
Hey Adrian, I need to ask something.
I already installed Python 2.7 with OpenCV 3.0 using this tutorial, but now I will need to upgrade to OpenCV 3.1 because I will need the extra modules inside the opencv_contrib. How can I do that? Do I need to delete anything first?
And because of problems with Matplotlib before this, I also think I need to download back the Python for its framework version. Will this effect anything?
Thanks.
Adrian Rosebrock
You don’t need to revert your Python version, just use an old version of matplotlib. I recommend
matplotlib==1.4.3
.As for uninstalling OpenCV, you should be able to delete all
libopencv*
files from/usr/local/lib
. You’ll also want to cleanup the Python OpenCV bindings (i.e., thecv2.so
file).Hilman
Thanks! As for the matplotlib issue, it is solved! Thank you so much! This makes me loves this blog even more! Keep up the good work of educating us! 🙂
Adrian Rosebrock
Awesome, I’m glad to hear it’s resolved! 🙂
Hilman
About uninstalling the OpenCV, can i just `sudo make uninstall` it? I’ve read that this is possible.
Adrian Rosebrock
I personally have never done this so I can’t say whether or not it would work. However, this would imply that you kept your original Makefile generated from CMake. Most people delete these after OpenCV has been compiled and installed.
Samvaran
Thank you for the great tutorial! It was very clear and incredibly helpful – there’s nothing else like this that I could find on the web.
I was able to build everything successfully and install everything just fine. My question is – if I want to redo the build and installation (e.g. if I want to install CUDA files and compile it with those added), and I repeat these steps (i.e. cmake and make), will anything bad happen given that all the files have already been installed? For instance, is there any kind of “uninstall” necessary, or can I just repeat these steps again without worrying?
Adrian Rosebrock
If you decide to recompile and re-install OpenCV, then nothing bad should happen. You’ll simply overwrite the existing files with the new ones.
ryan
thank you for the tutorial.
i’m getting this error when running the script though:
File “test_akaze.py”, line 15, in
detector = cv2.AKAZE_create()
AttributeError: ‘module’ object has no attribute ‘AKAZE_create’
any help would be appreciated.
Adrian Rosebrock
Hey Ryan — can you confirm which version of OpenCV you installed? Also, it would be worth checking the comments by “versionHell” and “aaz15” above. Both of them mentioned similar issues.
Lucky Dube
Hello Adrian, I’m a beginner and your tutorial was very useful. I managed to get all the way to step 9 without any issues but I don’t know how to place the code and the image in the same directory. This might be a very simple step but would it be possible for you to explain to me how to do it?
Thanks for your help
Adrian Rosebrock
All you need to do is download the image and the code. You can copy and paste the code into your favorite text editor and save the file. Both the code and the image should be saved to the same folder on your computer.
stefan
Thank you Adrian for your post on this issue which is LACKING from the opencv.org site. They cover installation to most ALL other OSes except OS X. I successfully followed your clear recipe and also especially appreciate all the thoughtful comments of your other readers. I am however getting an error with cmake –‘ffmpeg/avformat.h’ file not found. I wrote up all the details here:
https://stackoverflow.com/questions/36949053/opencv3-1-compilation-error-ffmpeg-avformat-h-file-not-found
How can I troubleshoot this?
Regarding the PYTHON2_NUMPY_INCLUDE_DIRS
the actual .h files are here:
~/.virtualenvs/cv/lib/python2.7/site-packages/numpy/core/include/numpy
not here
~/.virtualenvs/cv/lib/python2.7/site-packages/numpy/core/include
Well, I tracked down another error. Tried compiling with CUDA on but apparently that doesn’t work so easily on a mac. It has to do with compiler incompatibility with Clang and CUDA. Apparently I have to set a different compiler with CUDA_HOST_COMPILER. Do you have any insight about this?
I solved the ffmpeg problem. It seems there are certain source files that brew install ffmpeg doesn’t get. so i did
brew uninstall ffmpeg
brew install ffmpeg –build-from-source
Known issue.
https://github.com/Itseez/opencv/issues/6435
Adrian Rosebrock
Thanks for the comments Stefan! I’ve consolidated them into a single thread to make them a bit easier to read. Congrats on resolving the FFMPEG issue. As for CUDA, I try to avoid enabling that on OSX if at all possible. It’s always given me problems when compiling as well.
Greg n
These are super clear and useful instructions. Thanks for the taking the time and for all your responses to others’ issues. It meant I didn’t hit anything that hadn’t already been covered.
Adrian Rosebrock
Thanks for the kind words Greg, I’m happy the tutorial helped!
Mathilde
Hi,
Thank you for this tutorial, this really help me out! I did everything and it’s working great! But now I have to install matplotlib and I can’t manage to do that. What should I do ? Do I have to restart the c-make part ?
Adrian Rosebrock
The matplotlib library is completely independent from OpenCV, so there is absolutely no need to worry about CMake. What is the error you are getting with matplotlib?
Damon
Thanks for the great tutorial, Adrian! I really appreciate the effort! I’ve managed to get core OpenCV working, but I can’t seem to get any of the useful stuff working, like the SURF classifier. I’m told that modules such as xfeatures2d aren’t available. These are the modules found in opencv_contrib. I’ve followed your guide to the tee, but for some reason the extra modules simply are not linked to the core module. Then dylib files even exist at my /usr/local/lib folder. Any ideas?
Adrian Rosebrock
My favorite way to debug if the
opencv_contrib
modules are installed is to investigate the output of CMake. Under the list of components/packages to be built, you should see a list of OpenCV modules. Ideally, you’ll also see thexfeatures2d
module in their, indicating that your compile will include theopencv_contrib
. If you do not see these extra modules, then it’s likely that your path to theopencv_contrib
directory is incorrect. I would suggest deleting your currentbuild
directory, re-creating it, and then re-running CMake, supplying the correct path toopencv_contrib
.Sumanth Mallya
Brilliant tutorial ! Everything worked like clockwork, however when i was trying to use openCV in IDLE i was getting an cv2 not found error, after a little research and trying things out if found the solution, i had to edit my .bash_profile file to add a path using the pythonpath variable. Here is the what i added to the file after which it worked perfectly. Hope this helps someone with the same issue.
PS – Im guessing you can also ammend the below code for a different location of the cv2.so file
export PYTHONPATH=/Users/Sumanth/opencv/build/lib:$PYTHONPATH
Adrian Rosebrock
Are you referring to the GUI version of IDLE? If so, the GUI IDLE doesn’t place nice with Python virtual environments. Otherwise, if you want to access IDLE via command like, just be sure to execute the
workon
command first.Olivera
Hi Adrian. I need your help, please. I try to follow your directions to install openCV on El Capitan but I get error on the step 4. I installed virtualenv and virtualenvwrapper, but when I update the bash_profile with the lines you have it shows me “no such file found in the directory”. Also I can not create the cv virtual environment. When I add the command “mkvirtualenv cv” it shows me “the command not found”. I have been trying to installl for few days alredy but I’m not succeeding. Please, help me. Thank you in advance.
Adrian Rosebrock
In order to run
mkvirtualenv
, you’ll need to make sure you have your~/.bash_profile
updated properly. Try editing it using nano:$ nano ~/.bash_profile
shahram
I have exactly the same problem. Any help?
Vidhi Jain
For my system, even the sudo make install command seems to be failing. Any suggestions?
Adrian Rosebrock
If
sudo make install
isn’t working, then themake
command like failed as well. Check the output ofmake
to ensure that OpenCV compiled correctly.Mehdi
Awsome tutorial!
Adrian Rosebrock
Thanks Mehdi!
Geert
Thank you for this awesome and easy to follow tutorial. Now I want to use matplotlib but I do not get it to work. I tried to install it with pip within the virtual environment. There were no problems there but when I try to import matplotlib in my code which i’m running with pyCharm I get this error:
RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are Working with Matplotlib in a virtual enviroment see 'Working with Matplotlib in Virtual environments' in the Matplotlib FAQ
Please help me and tell me what i’m doing wrong. Thank you in advance.
Adrian Rosebrock
There are some know issues with Python virtual environments and the latest release of matplotlib that cause this error. As far as I know, there is no fix yet, but for the time being, you can use a previous version of matplotlib and it will work on OSX:
$ pip install matplotlib==1.4.3
If you already have matplotlib installed, make sure you uninstall it before you execute the above command.
Chris
Was wondering if anyone was having an issue when importing cv2 in python. The install for openCV worked great but when I try to import cv2 I get the following: ImportError: numpy.core.multiarray failed to import
Anyone have a fix?
Adrian Rosebrock
Hey Chris — it sounds like you do not have NumPy installed on your system or you do not have NumPy installed in your Python virtual environment. I would suggest going back to Step #5 and ensuring you have NumPy installed.
Chris
Thanks for the advice. I tired that to no avail. I removed all traces of NumPy and re installed it ensuring the paths are correct in the cmake but still get the error” ImportError: numpy.core.multiarray failed to import” I am a bit of a noob when it comes to working in the terminal so probably just missing something small.
Adrian Rosebrock
This definitely seems to be an issue either related to your
PYTHONPATH
or your Python virtual environment. Unfortunately, without physical access to your machine, I can’t diagnose what the exact issue is. Make sure you are in thecv
virtual environment before installing NumPy and running CMake.Tanya
Trying to do “pip install virtualenv virtualenvwrapper”. However, when I edit my .bash_profile as the instructions say and run “source ~/.bash_profile” I get the error “/usr/local/bin/virtualenvwrapper.sh: No such file or directory”. Then when I run “which virtualenv” to see where the virtualenv is being installed, I get “/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv”. I’ve tried uninstalling and then installing again, but that has not worked. How can I fix this problem?
Adrian Rosebrock
Hey Tanya — I suspect this is a Python versioning issue. Did you install Python via Homebrew? And if so, did you apply Step #3 wen updating your
.bash_profile
file? I would runwhich python
and see if it’s the same Python that virtualenv and virtualenvwrapper are installed on.Apple
Thanks for your tutorial, I have the similar problem. Trying to do “pip install virtualenv virtualenvwrapper”, but when I run “source ~/.bash_profile”, I was told “No module named virtualenvwrapper. virtualenvwrapper.sh: There was a problem running the initialization hooks. ” I am sure the output of ‘which python’ is /usr/local/bin/python, and I have run “pip install virtualenv virtualenvwrapper”
Adrian Rosebrock
Try running
pip freeze
and ensuring that both virtualenv and virtualenvwrapper are among the installed packages. If they are present, then the issue is likely due to the path updates to your.bash_profile
file.E
I have this same problem. When I run which python, I get “/usr/local/bin/python” but when I run which virtualenv, I get “/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv”
How do I make it so that the virtualenv is installed on the correct python?
Adrian Rosebrock
It’s hard to say what the exact issue is without physical access to your machine. What is the output of
which pip
? I get the impression that pip, for whatever reason, is using the original version, not the Homebrew version.MTS
Hello, i just using python 2.7 and will instal opencv, so i must using other hardware (rashberry) or can just using computer ?
Adrian Rosebrock
Hm, I’m not sure what you are asking in this comment. If you are using Python 2.7 on your OSX machine, follow this tutorial. If you are using a Raspberry Pi, follow one of these tutorials.
Mike Sharps
Brilliant tutorial. Followed instructions step by step and Installed Opencv 3.1.0 on El Capitan no problems. Ubuntu is next. What IDE / Dev environment do you recommend I’ve just been using either textmate or emacs for some basic python projects but not an IDE as such.
Also I’m not too sure where to go next to explore opencv, any suggestions ?
Adrian Rosebrock
If you’re just getting started learning OpenCV, then you should absolutely go through Practical Python and OpenCV. This book will help you get up to speed super quickly. It also covers a number of interesting computer vision projects including face detection, handwriting recognition, and identifying the covers of books.
As for an IDE, take a look at PyCharm. I detail how to setup PyCharm for computer vision development in this blog post.
joas
Hello Adrian, I can’t find cv2.so in the / site-packages when I exactly install everything . Please help
Adrian Rosebrock
Hey Joas — after
make
has finished executing, make sure you take a look in thebuild/lib
directory and see if thecv2.so
file is in there.minho
Thanks for your awesome tutorial!
I’m first time to python opencv and OSX.
I got error in ‘make -j4’ step like follows
how can I solve this problem ? T_T
Adrian Rosebrock
I assume based on this error message that you are using either OSX – El Capitan or macOS Sierra. Unfortunately, these versions of OSX have been breaking OpenCV builds because QTKit is no longer bundled with the OS and the OpenCV developers are not supporting AVFoundation. It’s a bit of a mess right now and I’m actually investigating it myself. In the meantime, I would suggest downgrading to OSX Yosemite (10.10) where QTKit is still found.
Alexander
One solution for this for now is to simply disable the videoio module while compiling. You can do that with this flag in cmake: “-D BUILD_opencv_videoio=OFF” (from https://github.com/opencv/opencv/issues/6913)
After that I also had another issue, “fatal error: ‘opencv2/highgui.hpp’ file not found” around 86% of the way through. I’m not sure if this is caused because I’m running Serria, but I couldn’t find anything online about it. Disabling the xphoto module let it compile though. (the flag is “BUILD_opencv_xphoto=OFF”)
Hopefully they’ll fix these issues soon though so we can recompile with these two modules.
Adrian Rosebrock
Thanks for the tip Alexander. I got OpenCV 3.1 to compile on El Capitan yesterday. I’m planning on trying Sierra later this weekend. I’ll be sure to turn my findings into a blog post 😉
Peter
Hi Alexander,
I have the same error too, could you help me please?
Thanks
Adrian Rosebrock
As I mentioned in the previous comment, I’ll be finalizing my steps and turning the result into a new blog post within the next couple of weeks.
Roger
Hi Adrian,
Your post has been really helpful, thank you very much. I have enrolled to your course and followed the tutorial so far, but hit the brick when tried to install the opencv 3.1.0 on macOS Sierra 10.12.
Since you have mentioned that you will post new updated steps, I was wondering if you have any update on this matter?
Many thanks
Adrian Rosebrock
Hey Roger — I’m planning on creating a brand new blog post for macOS Sierra. I’m also waiting for Sierra to stabilize and closing monitoring the OpenCV commits to determine the right time to create this blog post. Right now everything is too volatile.
Madeline
I am encountering this same problem now. Is there an updated solution? I would rather not downgrade to OSX Yosemite, but I need to compile OpenCV with the videoio module.
Adrian Rosebrock
Please follow my updated tutorials for macOS.
Lance Legel
You’re the boss, thanks so much.
Just a note that as of today, I wasn’t able to compile with 3.1.0 hardcoded into the git checkout; I had to simply work with the master branches for both opencv and opencv_contrib, following this error: http://answers.opencv.org/question/94067/help-analyze-make-error-in-opencv-contrib3/
Anyways, keep killing it, and best regards.
Adrian Rosebrock
Thanks for sharing Lance — very strange indeed!
Margareta
Great guide!
However I couldn’t install opencv without doing some modification on El captain. I did the following modifications:
1. Never checkout out a certain version from the gitrepo, I only cloned down the repo and skipped the checkout part for both opencv and opencv_contrib
2. Had -D INSTALL_C_EXAMPLES=ON instead of off as suggested.
Adrian Rosebrock
Great job getting OpenCV installed on your system Margareta! I’m in the process of creating updated OpenCV install tutorials for both El Capitan and macOS Sierra to avoid confusions like these in the future.
Roger
Hi Margareta,
Thanks you very much!
I have followed your steps and successfully installed opencv 3.1.0 on macOS Sierra 10.12; executed the test drive suggested in this tutorial, so far so good : )
To Adrian, I hope this information is useful for your new tutorials.
Kind regards
Belal C
I got around the issue with compiling on macOS Sierra by switching to the ‘pr7266’ branch for opencv and the ‘master’ branch for opencv_contrib (https://github.com/opencv/opencv/pull/7266).
I’m pretty sure the AVFoundation functionality developed to replace QTkit is merged with the master branch. not sure why it wasn’t compiling…
Anyway, thanks so much for this thorough guide Adrian – really helped me as a beginner to compiling + installing software (interesting to see the steps broken down!)
Adrian Rosebrock
Thanks for sharing Belal! Once we get another update to OpenCV (ideally v3.2) I’ll make another blog post on installing on OSX. I’d also like to see macOS Sierra mature a bit.
Alex Ogilvie
Hi Adrian,
Thanks for the tutorial. I’ve managed to get OpenCV installed within the virtual environment I set up, but need to have it installed on my main environment. When I am trying to run python scripts that use OpenCV from MATLAB, MATLAB cannot find the cv2 module. Do you have any idea how to get OpenCV onto the main machine?
Thanks,
Adrian Rosebrock
Hey Alex — I honestly haven’t used MATLAB in many years so I’m not sure regarding this.
Alex Ogilvie
I guess what I’m trying to ask is how do you access python from outside the virtual environment? I’ve been into the site-packages folder of the virtual environment and the main environment, and a lot of the files – particularly the .so and .py files – aren’t in the main environment. Could this be why it’s not working?
Adrian Rosebrock
Typically I would suggest not creating Python projects without a virtual environment. But if you must have access to OpenCV outside of your virtual environment(s) simply copy the
cv2.so
files into your systemsite-packages
directory.Christian Egglin
I figured it out using Belal’s solution, I guess I should have checked before I commented. But now I am having the problem around the 85% mark:
/Users/Christian/opencv/modules/python/src2/cv2.cpp:6:10: fatal error: ‘Python.h’ file not found
#include
Most people commenting seem to have suggested that it come from the CMake step at the -D PYTHON2_INCLUDE_DIR=/usr/local/Frameworks/Python.framework/Headers.
But Python.h is located there. I am not sure how to fix this. I am using Python 2.7 and have Sierra
Thanks again,
Christian
Adrian Rosebrock
Installing OpenCV on macOS Sierra is a major pain right now. I’m currently working on a tutorial to make the process easier. However, your
PYTHON2_INCLUDE_DIR
should look something like this:PYTHON2_INCLUDE_DIR=/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/include/python2.7
Keep in mind that you should be compiling against the Homebrew version of Python, not your system version.
Walid Ahmed
Hi Adrian
I have both OpenCV2.4 and OpenCV3 installed on my Mac with python.
My code now only sees how OpenCV2.4, can I direct my system to use OpenCV3?
Thanks
Adrian Rosebrock
It really depends on how you actually installed both OpenCV 2.4 and OpenCV 3. Without knowing that I can’t direct you.
Benabbou
Hi Adrian,
Thanks for this tutorial i find it very useful and explicit however I got stuck at Compiling error
I don’t really get what is the problem .
Benabbou
I solved the Problem by deleting OpenCv and Opencv_rep .. directories and Cloned new ones but this time I used the Master Version I didn’t check out on both of them, then I did The other steps .
Adrian Rosebrock
Please see my reply to Rakshith above where I have addressed this question.
Rakshith
Hey Adrian, I’m getting a fatal error at “make -j4” step.
Is there any fix to this?
Adrian Rosebrock
Hey Rakshith — this error is because you are using either El Capitan or macOS Sierra where QTKit is no longer used. OpenCV 3.2 will resolve this issue for good, but in the meantime, make sure you download the latest code from the GitHub via
git clone
and do not rungit clone
. This will ensure you are compiling against the bleeding edge version of OpenCV where the issue has been resolved.Rakshith
Yeah I am on Sierra. However Alexander had posted a work around, will that work on Sierra? Or can you please post steps to compile with the latest version?
Adrian Rosebrock
The solution is to simply checkout the latest version of OpenCV from GitHub instead of downloading a tagged .zip archive. This will indeed work on Sierra. I’ll be posting an updated tutorial covering macOS Sierra (ideally) within the next month.
Ajay
Adrian: you Rock. As of Nov 2016 this is still the best resource on how to install opencv from source in virtualenv on mac
Adrian Rosebrock
Thanks so much Ajay, I really appreciate that! 🙂 Congrats on getting OpenCV installed on your Mac.
Jacob
Thanks for this tutorial:
At “make -j4” I’m getting at fatal error at 31% that says “‘QTKit/QTKit.h’ file not found”
Any ideas how to solve this?
Adrian Rosebrock
Hey Jacob — it sounds like you’re using macOS Sierra. Please follow this updated tutorial as I state at the top of the blog post.
J
Is this http://www.mobileway.net/2015/02/14/install-opencv-for-python-on-mac-os-x/ –> a same setup for installing and running OpenCV and Python too?
Adrian Rosebrock
Install OpenCV via Homebrew is a different process. The post you linked is for OpenCV 2.4, not OpenCV 3. I’ll have an updated tutorial for OpenCV 3 + Homebrew online this Monday, December 19th 2016.
Gunnar Dittmar
Thanks for the tutorial. It works with OpenCV 3.2 as well.
Adrian Rosebrock
Awesome, glad to hear it Gunnar! 🙂
Syeda Hasan
Hey,
Thank so much for the installation guide.I am trying to detect face in a video and store it as a series of images at different time intervals (for instance: the video is about 1 minute long and I want to capture the face every 10 seconds -that is 6 times) and store it in different files, is there an easy way to do that?
Adrian Rosebrock
To start, you’ll want to determine the frame rate of your video. Most videos are in the range 24-32 frames per second. Then, you just set a counter. You detect a face. Then start your counter and wait (for example) 24 * 10 frames until you detect your next face.
Danny
Hi, I am a beginner. I followed every step above and have successfully installed the OpenCV. I have a question now. Right now I can only run the OpenCV-installed python in the terminal where I can access the virtual environment and it is not convenient to edit at all. When I try to write a program in the python IDLE without the terminal, I cannot import OpenCV anymore and I have to pretend it is imported. So is there any way to import OpenCV library while I am editing it, instead of only using OpenCV when running the program?
I don’t know if I clearly explained it, but hope you can get my point.
Thanks for your awesome tutorial again!
Adrian Rosebrock
Python IDLE does not respect virtual environments. You should use either (1) the terminal version of IDLE or (2) use Jupyter Notebooks. The GUI version of IDLE is not recommended.
sponge
hello, first thanks so much for ur installation guide, I just follow ur steps, but in the step 4, when I pip install virtualenv virtualenvwrapper, I will always have a problem that
No module named virtualenvwrapper
virtualenvwrapper.sh: There was a problem running the initialization hooks.
If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenvwrapper has been installed for
VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python and that PATH is
set properly.
I do not know how to solve it ,really hope ur advice
thanks so much
jazz hands
I have the same problem! any ideas?
Shivam Saini
let me know if you found the solution
Mirna
Thank you for the great tutorial, Adrian!
Adrian Rosebrock
No problem Mirna, I’m happy I could help 🙂
Pat
Adrian,
Thanks for posting this. I’m new to OpenCV and this has really helped me get up and running without any grief.
When I make my first million from OpenCV I’ll buy you a beer.
Adrian Rosebrock
Congrats on getting OpenCV installed Pat! I look forward to that beer 😉
Ed
Awesome tutorial, thank you!
I came across a build error on Mac 10.12.3:
changing the makelist file of freetype module made the trick 🙂
https://github.com/opencv/opencv_contrib/issues/919
Adrian Rosebrock
Thank you for sharing Ed!
zrb
I had the same problem. This works great, thanks!
Jaypee
I am having problem in the step 8 when I run the $ make -j4. Can yanyone help me fix it. It would be of great help. Thanks.
The error is as follows:
[ 30%] Building CXX object modules/videoio/CMakeFiles/opencv_videoio.dir/src/cap_qtkit.mm.o
/Users/akshalsharma/opencv/modules/videoio/src/cap_qtkit.mm:46:9: fatal error: ‘QTKit/QTKit.h’
file not found
Adrian Rosebrock
Please read the other comments before posting. This question has been addressed. You need to refer to this tutorial.
crazyfang
I met a question that fatal error: ‘Python.h’ file not found #include when i make.What should i do to solve it.Help…thanks
Adrian Rosebrock
Your PYTHON_LIBRARY configuration is incorrect. Double-check the path to your Python include directory.
Paul
How to clean everything and start over??
please help
Adrian Rosebrock
The easiest way? Re-install macOS/OSX. Otherwise without knowing what step you are having trouble with it’s impossible to provide any suggestion on how to clean and restart the process.
Guy Hoffman
Great tutorial!
Small comment – in OpenCV 3.2.0 you need to go to
~/opencv_contrib/modules/freetype/CMakeLists.txt
and replace
${freetype2_LIBRARIES} ${harfbuzz_LIBRARIES}
with
${FREETYPE_LIBRARIES} ${HARFBUZZ_LIBRARIES}
ARUN UPADHYAYA
Hi,Adrian,
I successfully executed step3 but while i am trying to execute step 4 its telling me that pip command not found then i tried to install pip using sudo easy_install pip but then its telling command not found,I am screwed please guide me further.
Thanks.
Edgar Acosta
USING OPEN CV IN OTHER PYTHON VIRTUAL ENVIRONMENT:
I follow this Procedure to Install Open CV… and It Works… I install it in the CV Virtual Environment..
But i need to use it in Tensor Flow, Tensor Flow is in another Virtual Environment. How can i use OpenCV in the Virtual Environment, is there any way …
Please help..
Adrian Rosebrock
Hey Edgar — simply access the Python virtual environment that has OpenCV installed and use “pip” to install TensorFlow, etc.:
nck
Thanks a lot. Everything was almost smooth.
1º I had to change my version for 2.7.13.
2º I had a problem with cmake which was solved in the comments.
3º Adding some code in step 4 which I found in stackexchange, because some code was missing.
Michelle
Hi Adrian! I’ve followed this tutorial in the past to download OpenCV in one of my computers and worked like a charm. However, now that I am installing it in another one I had the issue that when I type “which python” it still gives me the system version.
Further, when I type “which python2” it correctly gives me the /usr/local/bin location. Seems like the home-brew installation is installing python as such. At the end I followed an instruction that appeared in the terminal saying that if I wanted the /usr/bin/local version then I should add this path to the bash_profile: “/usr/local/opt/slash/openssl/bin:$PATH”
The installation worked when I did that but I still get /usr/bin after writing “which python”, and the new path above when I try “which python2”. Any thoughts on this?
Thanks a million!
Adrian Rosebrock
It’s hard to say without physical access to your machine, but it seems like your $PATH has been updated to point to your system install of Python before Homebrew. I would double-check your
.bash_profile
and try to debug this. $PATH issues can be a real pain to debug.Daniel
This had stumped me too for a while, but it seems since the original publishing of this article that the requirements for pointing to the Homebrew version of Python have changed slightly (possibly could update article?).
As per the caveats of `brew info python`:
> This formula installs a python2 executable to /usr/local/bin.
If you wish to have this formula’s python executable in your PATH then add
the following to ~/.bash_profile:
export PATH=”/usr/local/opt/python/libexec/bin:$PATH”
So the initial `usr/local/bin` for Homebrew, and the above path for Homebrew’s Python. Works after that!
Adrian Rosebrock
Thanks for sharing Daniel!
Daniel YEH
I added export PATH=”/usr/local/opt/python/libexec/bin:$PATH” to the bash profile and used source command. After that, all of my command can’t work!
It showed command not found.
I need to type the following code to let terminal work properly:
export PATH=”/usr/bin:/bin:/usr/sbin:/sbin”
export PATH=”/usr/local/bin:/usr/local/sbin:$PATH”
but my problem of python”2″ didn’t solve…
David
I struggled with this too because no matter what, “which python” still pointed to my system Python rather than brew’s.
However, “which python2” points to the brew Python:
It is also good to check
pip
:The next step and trouble is when running the
virtualenvwrapper.sh
script from your.bash_profile
.It will complain when you source your
.bash_profile
after adding the line:source /usr/local/bin/virtualenvwrapper.sh
:That prompted me to read and modify that script.
$ sudo vim /usr/local/bin/virtualenvwrapper.sh
on Line 50 change
VIRTUALENVWRAPPER_PYTHON="$(command \which python)"
_to_
VIRTUALENVWRAPPER_PYTHON="$(command \which python2)"
That will get the right path to Python2 for you (brew’s Python).
Then:
$ source ~/.bash_profile
And now you’re ready to:
$ mkvirtualenv cv -p python2
and if you want python3
$ mkvirtualenv cvpy3 -p python3
Hopefully this helps someone and isn’t just a one off issue that I’ve had to figure out.
kram
I’m still getting the same complaint even after editing the virtualenvwrapper.sh, I changed python to python3 as it is my brew’s Python. any idea what else can be wrong?
Adrian Rosebrock
I actually was working on this problem yesterday. Update your
.bash_profile
to look like this:Then
source
it again. From there it should work. You might also have to edit thevirtualenvwrapper.sh
file and ensure it has its original contents (I didn’t have to edit the file).Allan
Hello,
Thanks for the tutorial. I am having an issue with step #3. Running “which python” still returns usr/bin/python.
However, “which python2” returns usr/local/bin/python2.
How do I get “which python” to return the expected output? My .bash_profile looks OK.
Thanks,
Allan
Adrian Rosebrock
This is an update to Homebrew on how it handles the “python” command. You can use “python2” throughout the rest of this tutorial and it will work as expected.
Marco
FYI, cv2.drawKeypoints() is currently broken:
https://github.com/opencv/opencv/issues/13406
Adrian Rosebrock
Thanks for the heads up, Marco!