Compiling OpenCV via source gives you complete and total control over which modules you want to build, how they are built, and where they are installed.
All this control can come at a price though.
The downside is that determining the correct CMake paths to your Python interpreter, libraries, and include directories can be non-trivial, especially for users who are new to OpenCV/Unix systems.
That begs the question…
“Is there an easier way to install OpenCV on macOS? A way that avoids the complicated CMake configuration?”
It turns out, there is — just use Homebrew, what many consider to be “the missing package manager for Mac”.
So, is it really that easy? Just can a few simple keystrokes and commands can be used to avoid the hassle and install OpenCV 3 without the headaches?
Well, there’s a little more to it than that…but the process is greatly simplified. You lose a bit of control (as compared to compiling from source), but what you gain is an easier to follow path to installing OpenCV on your Mac system.
To discover the easy way to install OpenCV 3 on macOS via Homebrew, just keep reading.
Install OpenCV 3 on macOS with Homebrew (the easy way)
The remainder of this blog post demonstrates how to install OpenCV 3 with both Python 2.7 and Python 3 bindings on macOS via Homebrew. The benefit of using Homebrew is that it greatly simplifies the install process (although it can pose problems of its own if you aren’t careful) to only a few set of commands that need to be run.
If you prefer to compile OpenCV from source with Python bindings on macOS, please refer to these tutorials:
Step #1: Install XCode
Before we can install OpenCV 3 on macOS via Homebrew, we first need to install Xcode, a set of software development tools for the Mac Operating System.
The easiest method to download and install Xcode is to use the included App Store application on your macOS system. Simply open up App Store, search for “Xcode” in the search bar, and then click the “Get” button:
Depending on your internet connection and system speed, the download and install process can take anywhere from 30 to 60 minutes. I would suggest installing Xocde in the background while you are getting some other work done or going for a nice long walk.
Accept the Apple developer license
I’m assuming that you’re working with a fresh install of macOS and Xcode. If so, you’ll need to accept the developer license before continuing. Personally, I think this is easier to do via the terminal. Just open up a terminal and execute the following command:
$ sudo xcodebuild -license
Scroll to the bottom of the license and accept it.
If you have already installed Xcode and previously accepted the Apple developer license, you can skip this step.
Install the Apple Command Line Tools
Now that Xcode is installed and we have accepted the Apple developer license, we can install the Apple Command Line Tools. These tools include packages such as make, GCC, clang, etc. This is a required step, so make you install the Apple Command line tools via:
$ sudo xcode-select --install
When executing the above command you’ll see a confirmation window pop up asking you to approve the install:
Simply click the “Install” button to continue. The actual install process of Apple Command Line Tools should take less than a 5 minutes.
If you haven’t already, be sure you have accepted the Xcode license using the following command:
$ sudo xcodebuild -license
Step #2: Install Homebrew
We are now ready to install Homebrew, a package manager for macOS. You can think of Homebrew as the macOS equivalent of the Ubuntu/Debian-based apt-get.
Installing Homebrew is dead simple — simply copy and paste the command below the “Install Homebrew” section of the Homebrew website (make sure you copy and paste the entire command into your terminal). I have included the command below as reference:
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
After Homebrew installs you should make sure the package definitions (i.e., the instructions used to install a given library/package) are up to date by executing the following command:
$ brew update
Now that Homebrew is successfully installed and updated, we need to update our
~/.bash_profile file so that it searches the Homebrew path for packages/libraries before it searches the system path. Failure to complete this step can lead to confusing errors, import problems, and segfaults when trying to utilize Python and OpenCV, so make sure you update your
~/.bash_profile file correctly!
~/.bash_profile file may or may not already exist on your system. In either case, open it with your favorite text editor (I’ll be using
nano in this example):
$ nano ~/.bash_profile
And then insert the following lines at the bottom of the file (if
~/.bash_profile does not exist the file will be empty — this is okay, just add the following lines to the file):
# Homebrew export PATH=/usr/local/bin:$PATH
All this snippet is doing is updating your
PATH variable to look for libraries/binaries along the Homebrew path before it searches the system path.
After updating the
~/.bash_profile file, save and exit your text editor.
To make sure you are on the right path, I have included a screenshot of my
~/.bash_profile below so you can compare it to yours:
~/.bash_profile may look very different than mine — that’s okay! Just make sure you have included the above Homebrew snippet in your file, followed by successfully saving and editing the editor.
Finally, we need to manually
~/.bash_profile file to ensure the changes have been reloaded:
$ source ~/.bash_profile
The above command only needs to be executed once. Whenever you open up a new terminal, login, etc., your
.bash_profile file will be automatically loaded and sourced for you.
Step #3: Install Python 2.7 and Python 3 using Homebrew
The next step is to install the Homebrew versions of Python 2.7 and Python 3. It is considered bad form to develop against the system Python as your main interpreter. The system version of Python should serve exactly that — system routines.
Instead, you should install your own version of Python that is independent from the system install. Using Homebrew, we can install both Python 2.7 and Python 3 using the following command:
$ brew install python python3
At the time of this writing the current Python versions installed by Homebrew are Python 2.7.12 and Python 3.5.2.
As a sanity check, let’s confirm that you are using the Homebrew version of Python rather than the system version of Python. You can accomplish this via the
$ which python /usr/local/bin/python $ which python3 /usr/local/bin/python3
Inspect the output of
which closely. If you are see
/usr/local/bin/python3 for each of the paths then you are correctly using the Homebrew versions of Python. However, if the output is instead
/usr/bin/python3 then you are incorrectly using the system version of Python.
If you find yourself in this situation you should:
- Go back to Step #2 and ensure Homebrew installed without error.
- Check that
brew install python python3finished successfully.
- You have correctly updated your
~/.bash_profilefile and reloaded the changes via
~/.bash_profileshould look similar to mine in Figure 3 above.
Check your Python versions
After installing Python 2.7 and Python 3, you’ll want to check your Python version numbers using the following commands:
$ python --version Python 2.7.10 $ python3 --version Python 3.5.0
In particular, pay attention to both the major and minor version numbers. For the first command, my major Python version is 2 and the minor version is 7. Similarly, for the second command my major Python version is 3 and the minor version is 5.
The reason I bring this up is because file paths can and will change based on your particular Python version numbers. The instructions detailed in this tutorial will successfully install OpenCV via Homebrew on your macOS machine provided you pay attention to your Python version numbers.
For example, if I were to tell you to check the
site-packages directory of your Python 3 install and provided an example command of:
$ ls /usr/local/opt/opencv3/lib/python3.5/site-packages/
You should first check your Python 3 version. If the
python3 --version command above reported 3.6, then you would need to update your path to be:
$ ls /usr/local/opt/opencv3/lib/python3.6/site-packages/
python3.5 was changed to
Forgetting to check and validate file paths is a common mistake I see readers make when trying to install OpenCV on their macOS machines for the first time. Do not blindly copy and paste commands and file paths. Instead, take the time to validate your file paths based on your Python version numbers. Doing so will ensure your commands are correctly constructed and will help you immensely when installing OpenCV for the first time.
Step #4: Install OpenCV 3 with Python bindings on macOS using Homebrew
Now that we have installed the Homebrew versions of Python 2.7 and Python 3 we are now ready to install OpenCV 3.
Tap the “homebrew/science” repo
The first step is to add the
homebrew/science repository to the set of packages we are tracking. This allows us to access the formulae to install OpenCV. To accomplish this, just use the following command:
$ brew tap homebrew/science
Understanding the “brew install” command
To install OpenCV on our macOS system via Homebrew we are going to use the
brew install command. This command accepts the name of a package to install (like Debian/Ubuntu’s apt-get), followed by set of optional arguments.
The base of our command is:
brew install opencv3 ; however, we need to add some additional parameters.
The most important set of parameters are listed below:
--with-contrib: This ensures that the opencv_contrib repository is installed, giving us access to additional, critical OpenCV features such as SIFT, SURF, etc.
--with-python3: OpenCV 3 + Python 2.7 bindings will be automatically compiled; however, to compile OpenCV 3 + Python 3 bindings we need to explicitly supply the
--HEAD: Rather than compiling a tagged OpenCV release (i.e., v3.0, v3.1, etc.) the
--HEADswitch instead clones down the bleeding-edge version of OpenCV from GitHub. Why would we bother doing this? Simple. We need to avoid the QTKit error that plagues macOS Sierra systems with the current tagged OpenCV 3 releases (please see the “Avoiding the QTKit/QTKit.h file not found error” section of this blog post for more information)
You can see the full listing of options/switches by running
brew info opencv3 , the output of which I’ve included below:
$ brew info opencv3 ... --32-bit Build 32-bit only --c++11 Build using C++11 mode --with-contrib Build "extra" contributed modules --with-cuda Build with CUDA v7.0+ support --with-examples Install C and python examples (sources) --with-ffmpeg Build with ffmpeg support --with-gphoto2 Build with gphoto2 support --with-gstreamer Build with gstreamer support --with-jasper Build with jasper support --with-java Build with Java support --with-libdc1394 Build with libdc1394 support --with-opengl Build with OpenGL support (must use --with-qt5) --with-openni Build with openni support --with-openni2 Build with openni2 support --with-python3 Build with python3 support --with-qt5 Build the Qt5 backend to HighGUI --with-quicktime Use QuickTime for Video I/O instead of QTKit --with-static Build static libraries --with-tbb Enable parallel code in OpenCV using Intel TBB --with-vtk Build with vtk support --without-eigen Build without eigen support --without-numpy Use a numpy you've installed yourself instead of a Homebrew-packaged numpy --without-opencl Disable GPU code in OpenCV using OpenCL --without-openexr Build without openexr support --without-python Build without Python support --without-test Build without accuracy & performance tests --HEAD Install HEAD version
For those who are curious, the Homebrew formulae (i.e., the actual commands used to install OpenCV 3) can be found here. Use the parameters above and the install script as a reference if you want to add any additional OpenCV 3 features.
We are now ready to install OpenCV 3 with Python bindings on your macOS system via Homebrew. Depending on the dependencies you do or do not already have installed, along with the speed of your system, this compilation could easily take a couple of hours, so you might want to go for a walk once you kick-off the install process.
Installing OpenCV 3 with Python 3 bindings via Homebrew
To start the OpenCV 3 install process, just execute the following command:
$ brew install opencv3 --with-contrib --with-python3 --HEAD
This command will install OpenCV 3 on your macOS system with both Python 2.7 and Python 3 bindings via Homebew. We’ll also be compiling the latest, bleeding edge version of OpenCV 3 (to avoid any QTKit errors) along with
opencv_contrib support enabled.
Update — 15 May 2017:
There was recently an update to the Homebrew formula used to install OpenCV on your macOS machine that may cause two types of errors.
Ideally the Homebrew formula will be updated in the future to prevent these errors, but in meantime, if you encounter either of the errors below:
opencv3: Does not support building both Python 2 and 3 wrappers
No such file or directory 3rdparty/ippicv/downloader.cmake
Then be sure to refer to this updated blog post where I provide solutions to both of the errors.
As I mentioned, this install process can take some time so consider going for a long walk while OpenCV installs. However, make sure your computer doesn’t go to sleep/shut down while you are gone! If it does, the install process will break and you’ll have to restart it.
Assuming OpenCV 3 installed without a problem, your terminal output should look similar to mine below:
However, we’re not quite done yet.
You’ll notice a little note at the bottom of the install output:
If you need Python to find bindings for this keg-only formula, run: echo /usr/local/opt/opencv3/lib/python2.7/site-packages >> /usr/local/lib/python2.7/site-packages/opencv3.pth
This means that our Python 2.7 + OpenCV 3 bindings are now installed in
/usr/local/opt/opencv3/lib/python2.7/site-packages , which is Homebrew path to the OpenCV compile. We can verify this via the
$ ls -l /usr/local/opt/opencv3/lib/python2.7/site-packages total 6944 -r--r--r-- 1 admin admin 3552288 Dec 15 09:28 cv2.so
However, we need to get these bindings into
/usr/local/lib/python2.7/site-packages/ , which is the
site-packages directory for Python 2.7. We can do this by executing the following command:
$ echo /usr/local/opt/opencv3/lib/python2.7/site-packages >> /usr/local/lib/python2.7/site-packages/opencv3.pth
The above command creates a
.pth file which tells Homebrew’s Python 2.7 install to look for additional packages in
/usr/local/opt/opencv3/lib/python2.7/site-packages — in essence, the
.pth file can be considered a “glorified sym-link”.
At this point you now have OpenCV 3 + Python 2.7 bindings installed!
However, we’re not quite done yet…there is still a few extra steps we need to take for Python 3.
Handling the Python 3 issue
--with-python3 option we supplied to
brew install opencv3 ?
Well, this option did work (although it might not seem like it) — we do have Python 3 + OpenCV 3 bindings installed on our system.
Note: A big thank you to Brandon Hurr for pointing this out. For a long time I thought the
--with-python3 switch simply wasn’t working.
However, there’s a bit of a problem. If you check the contents of
/usr/local/opt/opencv3/lib/python3.5/site-packages/ you’ll see that our
cv2.so file has a funny name:
$ ls -l /usr/local/opt/opencv3/lib/python3.5/site-packages/ total 6952 -r--r--r-- 1 admin admin 3556384 Dec 15 09:28 cv2.cpython-35m-darwin.so
I have no idea why the Python 3 + OpenCV 3 bindings are not named
cv2.so as they should be, but the same is true across operating systems. You’ll see this same issue on macOS, Ubuntu, and Raspbian.
Luckily, the fix is easy — all you need to do is rename
$ cd /usr/local/opt/opencv3/lib/python3.5/site-packages/ $ mv cv2.cpython-35m-darwin.so cv2.so $ cd ~
From there, we can create another
.pth file, this time for the Python 3 + OpenCV 3 install:
$ echo /usr/local/opt/opencv3/lib/python3.5/site-packages >> /usr/local/lib/python3.5/site-packages/opencv3.pth
At this point you now have both Python 2.7 + OpenCV 3 and Python 3 + OpenCV 3 installed on your macOS system via Homebrew.
Verifying that OpenCV 3 has been installed
Here are the commands I use to validate that OpenCV 3 with Python 2.7 bindings are working on my system:
$ python Python 2.7.12 (default, Oct 11 2016, 05:20:59) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import cv2 >>> cv2.__version__ '3.1.0-dev' >>>
The screenshot below shows how to import the OpenCV 3 bindings into a Python 3 shell as well:
Congratulations, you have installed OpenCV 3 with Python bindings on your macOS system via Homebrew!
But if you’re a longtime reader reader of this blog, you know that I use Python virtual environments extensively — and you should too.
Step #5: Setup your Python virtual environment (optional)
You’ll notice that unlike many of my previous OpenCV 3 install tutorials, Homebrew does not make use of Python virtual environments, a best practice when doing Python development.
While Steps #5-#7 are optional, I highly recommend that you do them to ensure your system is configured in the same way as my previous tutorials. You’ll see many tutorials on the PyImageSearch blog leverage Python virtual environments. While they are indeed optional, you’ll find that in the long run they make your life easier.
Installing virtualenv and virtualenvwrapper
The virtualenv and virtualenvwrapper packages allow us to create separate, independent Python virtual environments for each project we are working on. I’ve mentioned Python virtual environments many times before on this blog so I won’t rehash what’s already been said. Instead, if you are unfamiliar with Python virtual environments, how they work, and why we use them, please refer to the first half of this blog post. I also recommend this excellent tutorial on the RealPython.com blog that takes a more in-depth dive into Python virtual environments.
To install both
virtualenvwrapper , just use
$ pip install virtualenv virtualenvwrapper
After both packages have successfully installed, you’ll need to update your
~/.bash_profile file again:
$ nano ~/.bash_profile
Append the following lines to the file:
# Virtualenv/VirtualenvWrapper source /usr/local/bin/virtualenvwrapper.sh
After updating, your
~/.bash_profile should look similar to mine below:
Once you have confirmed that your
~/.bash_profile has been created, you need to refresh your shell by using the
$ source ~/.bash_profile
This command only needs to be executed once. Assuming that your
~/.bash_profile has been updated correctly, it will automatically be loaded and
source ‘d each time you open a new shell, login, etc.
Create your Python virtual environment
We are now ready to use the
mkvirtualenv command to create a Python virtual environment named
cv (for “computer vision”).
For Python 2.7 use the following command:
$ mkvirtualenv cv -p python
For Python 3 use this command:
$ mkvirtualenv cv -p python3
-p switch controls which Python version is used to create your virtual environment. Please note that each virtual environment needs to be uniquely named so if you want to create two separate virtual environments, one for Python 2.7 and another for Python 3, you’ll want to make sure that each environment has a separate name — both cannot be named “cv”.
mkvirtualenv command only needs to be executed once. To access the
cv Python virtual environment after you have already created it, just use the
$ workon cv
To visually validate you are in the
cv virtual environment, just examine your command line. If you see the text
(cv) preceding the prompt, then you are in the
cv virtual environment:
Otherwise, if you do not see the
cv text, then you are not in the
cv virtual environment:
The only Python prerequisite for OpenCV is NumPy, a scientific computing package.
To install NumPy, first make sure you are in the
cv virtual environment and then let
pip handle the actual installation:
$ pip install numpy
Step #6: Sym-link the OpenCV 3 bindings (optional)
We are now ready to sym-link in the
cv2.so bindings into our
cv virtual environment. I have included the commands for both Python 2.7 and Python 3, although the process is very similar.
For Python 2.7
To sym-link the
cv2.so bindings into your Python 2.7 virtual environment named
cv , use these commands:
$ cd ~/.virtualenvs/cv/lib/python2.7/site-packages/ $ ln -s /usr/local/opt/opencv3/lib/python2.7/site-packages/cv2.so cv2.so $ cd ~
For Python 3:
To sym-link the
cv2.so bindings installed via Homebrew to your Python 3 virtual environment (named
cv ), execute these commands:
$ cd ~/.virtualenvs/cv/lib/python3.5/site-packages/ $ ln -s /usr/local/opt/opencv3/lib/python3.5/site-packages/cv2.so cv2.so $ cd ~
Repeat as necessary
If you would like to have OpenCV 3 bindings installed for both Python 2.7 and Python 3, then you’ll want to repeat Step #5 and Step #6 for both Python versions. This includes creating a uniquely named Python virtual environment, installing NumPy, and sym-linking in the
Step #7: Test your OpenCV 3 install (optional)
To verify that your OpenCV 3 + Python + virtual environment install on macOS is working properly, you should:
- Open up a new terminal window.
- Execute the
workoncommand to access the
cvPython virtual environment.
- Attempt to import your Python + OpenCV 3 bindings on macOS.
Here are the exact commands I used to validate that my Python virtual environment + OpenCV install are working correctly:
$ workon cv $ python >>> import cv2 >>> cv2.__version__ '3.1.0-dev' >>>
Note that the above output demonstrates how to use OpenCV 3 + Python 2.7 with virtual environments.
I also created an OpenCV 3 + Python 3 virtual environment as well (named
py3cv3 ), installed NumPy, and sym-linked the OpenCV 3 bindings. The output of me accessing the
py3cv3 virtual environment and importing OpenCV can be seen below:
So, what’s next?
Congrats! You now have a brand new, fresh install of OpenCV on your macOS system — and I’m sure you’re just itching to leverage your install to build some awesome computer vision apps…
…but I’m also willing to bet that you’re just getting started learning computer vision and OpenCV, and probably feeling a bit confused and overwhelmed on exactly where to start.
Personally, I’m a big fan of learning by example, so a good first step would be to have some fun and read this blog post on detecting cats in images/videos. This tutorial is meant to be very hands-on and demonstrate how you can (quickly) build a Python + OpenCV application to detect the presence of cats in images.
And if you’re really interested in leveling-up your computer vision skills, you should definitely check out my book, Practical Python and OpenCV + Case Studies. My book not only covers the basics of computer vision and image processing, but also teaches you how to solve real-world computer vision problems including face detection in images and video streams, object tracking in video, and handwriting recognition.
So, let’s put that fresh install of OpenCV 3 on your macOS system to good use
What's next? I recommend PyImageSearch University.
25 total classes • 37h 19m video • Last updated: 7/2021
★★★★★ 4.84 (128 Ratings) • 10,597 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:
- ✓ 25 courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 25 Certificates of Completion
- ✓ 37h 19m on-demand video
- ✓ Brand new courses released every month, ensuring you can keep up with state-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Access to centralized code repos for all 400+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
In today’s blog post I demonstrated how to install OpenCV 3 with Python 2.7 and Python 3 bindings on your macOS system via Homebrew.
As you can see, utilizing Homebrew is a great method to avoid the tedious process of manually configuring your CMake command to compile OpenCV via source (my full list of OpenCV install tutorials can be found on this page).
The downside is that you lose much of the control that CMake affords you.
Furthermore, while the Homebrew method certainly requires executing less commands and avoids potentially frustrating configurations, it’s still worth mentioning that you still need to do a bit of work yourself, especially when it comes to the Python 3 bindings.
These steps also compound if you decide to use virtual environments, a best practice when doing Python development.
When it comes to installing OpenCV 3 on your own macOS system I would suggest you:
- First try to install OpenCV 3 via source. If you run into considerable trouble and struggle to get OpenCV 3 to compile, use this as an opportunity to teach yourself more about Unix environments. More times than not, OpenCV 3 failing to compile is due to an incorrect CMake parameter that can be correctly determined with a little more knowledge over Unix systems, paths, and libraries.
- Use Homebrew as a fallback. I would recommend using the Homebrew method to install OpenCV 3 as your fallback option. You lose a bit of control when installing OpenCV 3 via Homebrew, and worse, if any sym-links break during a major operating system upgrade you’ll struggle to resolve them. Don’t get me wrong: I love Homebrew and think it’s a great tool — but make sure you use it wisely.
Anyway, I hope you enjoyed this blog post! And I hope it helps you get OpenCV 3 installed on their macOS systems.
If you’re interested in learning more about OpenCV, computer vision, and image processing, be sure to enter your email address in the form below to be notified when new blog posts + tutorials are published!
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.