Install OpenCV 4 on macOS

This tutorial provides step-by-step instructions to install OpenCV 4 (with Python bindings) on your macOS machine.

While OpenCV 4 has not been officially released yet, a release is expected in autumn 2018. In the meantime, you can compile and install OpenCV 4 from source on your macOS system using the pre-release on GitHub.

Once OpenCV 4 is officially released I will update these install instructions as well.

To learn how to install OpenCV 4 on macOS, just keep reading.

Looking for the source code to this post?
Jump right to the downloads section.

Install OpenCV 4 on macOS

In this blog post we’re going to install OpenCV 4 on macOS. OpenCV 4 is packed with new features, many of which are deep-learning focused.

Note: If you landed on the wrong install tutorial (perhaps you want to install OpenCV on Ubuntu or your Raspberry Pi), then you should visit my OpenCV installation guides page. I post links to all my OpenCV install tutorials there.

First, we’ll install Xcode and set up Homebrew.

From there, we’ll establish Python virtual environments.

Then we’ll compile OpenCV 4 from source. Compiling from source allows us to have full control over the compile and build as well as to install the full OpenCV 4 build. I’ll cover alternative methods (pip and Homebrew) in future installation guides (neither of these methods can be covered until OpenCV 4 is officially released).

Finally, we’ll test out our OpenCV 4 install and get our feet wet with a real OpenCV project.

Let’s begin!

Step #1: Install Xcode

First we need to install Xcode.

To install Xcode, fire up the Apple App Store, find the Xcode app, and install. You’ll need to wait patiently as this figure indicates:

Figure 1: Xcode is a dependency for Homebrew and therefore OpenCV 4 on macOS. To install Xcode, launch the App Store, find Xcode, and run the installation.

After Xcode has installed we need to accept a license agreement. Launch a terminal and enter the following command:

To accept the license, simply scroll down and accept it.

Once you’ve accepted the license agreement, let’s install Apple Command Line Tools. This is required, so that you’ll have make , gcc , clang , etc. You can install the tools via:

Figure 2: Installing Apple Command Line Tools on macOS.

Figure 2: Installing Apple Command Line Tools on macOS.

Click the “Install” button and wait about 5 minutes for the installation to complete.

Step #2: Install Homebrew

For this step we’re going to install the Mac community package manager, Homebrew.

Homebrew runs on Ruby which is a popular programming language. When you’re ready, copy the entire command below to install Homebrew:

Note: Make sure you use the <=> button in the code block above to expand the code block before you copy and paste. If you don’t expand the code block you may end up copying pasting part of the command, which will ultimately end with an error installing Homebrew.

Homebrew commands are shortened to brew .

Let’s update the Homebrew definitions:

And now let’s edit our Mac’s bash profile. This script is run each time you launch a terminal. For simplicity, I suggest the nano text editor. If you’re more comfortable with vim or emacs, then go for it.

Edit your bash profile with nano using the following command:

Once you’re actively editing the file, append the following lines to the end to update your PATH :

From there, save the profile. If you’re using nano, you’ll see the shortcut keys at the bottom of the window which demonstrate how to save (write) and exit.

Once you’re back in bash, source your bash profile:

A tool you’ll learn to love is wget . All wget  does is download files from the command line. We can use Homebrew to install wget:

Now let’s install Python 3:

To verify your Python 3 install, use which :

If you see /usr/local/bin/python3  you are using the Homebrew Python (which is what we desire). If you see /usr/bin/python3  then you are using the system Python and you likely need to fix your bash profile and/or source it.

Take the time now to verify you are using the Homebrew version of Python and not the system version.

Step #3: Install Python dependencies for OpenCV 4

We’re going to install the Python dependencies for OpenCV 4 in this step.

Taking advantage of the wget  tool that we just installed, let’s download and install pip (a Python package manager):

Now that we have pip installed, we can install virtualenv and virtualenvwrapper, two tools for managing virtual environments. Python virtual environments are a best practice for Python development and I strongly urge you to take full advantage of them.

Each week, I receive countless emails and blog comments about problems that can be avoided with use of virtual environments. Virtual environments are different than virtual machines despite the similar name.

To learn about virtual environments, I suggest you give this article a read.

Let’s install virtualenv  and virtualenvwrapper , then do a bit of cleanup:

From there, we need to edit our bash profile again so that these two tools work properly.

Fire up nano (or your preferred text editor):

And then add these lines to the end of the file:

Figure 3: Using the nano text editor to edit the ~/.bash_profile prior to installing OpenCV 4 for macOS.

Pro-tip: You can use bash commands to append to the file without opening an editor:

Then source the file:

You’ll see several lines printed in your terminal indicating that virtualenvwrapper is setup.

The virtualenvwrapper  tool provides us a number of terminal commands:

  • mkvirtualenv <env_name> <options> : Used to “make a virtual environment”
  • rmvirtualenv <env_name> : Destroys a virtual environment
  • workon <env_name> : Activates a virtual environment
  • deactivate : Deactivates the current virtual environment
  • You’ll want to read the docs for more information.

Let’s take advantage of the first command to create a Python virtual environment for OpenCV:

Notice that cv  is the name of our environment and that I am creating a Python 3 (controlled by the -p python3  switch) environment.

You may name your environment differently if you’d like. I actually like to name my environments like so:

  • py3cv4
  • py3cv3
  • py2cv2
  • etc.

Here my py3cv4  virtual environment can be used for Python 3 + OpenCV 4. My py3cv3  virtual environment is used for Python 3 and OpenCV 3. And my py2cv2  environment can be used to test legacy Python 2.7 + OpenCV 2.4 code. These virtual environment names are easy to remember and allow me to switch between OpenCV + Python versions (nearly) seamlessly.

Next, let’s install NumPy while we’re inside the environment.

Chances are, the environment is already active (indicated by (cv)  preceding your bash prompt). Just in case, let’s workon  (activate) the environment:

Figure 4: We are “in” the cv virtual environment as is denoted by (cv) before the bash prompt. This is necessary prior to installing packages and compiling OpenCV 4.

Each time you wish to use the environment or install packages into it you should use the workon  command.

Now that our environment is activated, we can install NumPy:

Step #4: Compile OpenCV 4 for macOS

Compiling from source gives you the most control over your build as opposed to package managers such as pip, Homebrew, and Anaconda.

Package managers are convenient for sure and I’ll cover them in a future installtion tutorial, I just want to give you fair warning — while they appear easy on the surface, you won’t be able to get the latest revision of OpenCV and in some cases it won’t work well with virtual environments. You also might be missing features.

I still compile from source all the time and you should definitely learn how if you’re serious about working with OpenCV.

Checkout OpenCV from GitHub

Since OpenCV is still in “pre-release”, zips aren’t yet published to the archive area of GitHub. Therefore, we’ll clone the repositories from GitHub and checkout known-good commits. You could checkout the HEAD as well, but I’ve verified that the following revision is relatively stable.

Let’s navigate to our home folder and clone both opencv and opencv_contrib. The contrib repo contains extra modules and functions which we frequently use here on the PyImageSearch blog. You should be installing the OpenCV library with the additional contrib modules as well.

When you’re ready, just follow along to clone down both the opencv  and opencv_contrib  repositories:

From there, let’s be sure to checkout specific commits from each repository, ensuring you’re able to replicate my install:

Once OpenCV 4 is officially released I’ll be updating this guide to use simple wget  commands instead of requiring you to clone down the entire repository and checkout a specific commit.

Compile OpenCV4 from source

Now that opencv  and opencv_contrib  are downloaded and ready to go, let’s employ CMake to setup our compile and Make to perform the compilation.

Navigate back to your OpenCV repo and create + enter a build  directory:

Now we’re ready for CMake. Be sure to use the  workon  command before executing the cmake  command as shown:

Note: For the above CMake command, I spent considerable time creating, testing, and refactoring it. It is effectively self-configuring with no work required on your part. I’m confident that it will save you time and frustration if you use it exactly as it appears. Make sure you click the “<=>” button in the toolbar of the code block above to expand the code block. This will enable you to copy and paste the entire command (it’s pretty lengthy).

Once CMake has finished, scroll up (ever so slightly) until you see the following information in your terminal:

Figure 5: Inspecting CMake output while installing OpenCV 4 on macOS is important. Be sure that your cv virtual environment is being used for Python and NumPy.

Your output should look very similar to mind. What you’re looking for is to ensure that your Python 3 interpreter and NumPy in the virtual environment will both be used. If you don’t see this, then you likely executed CMake without being “in” the cv  virtual environment (or whatever you named your Python virtual environment). If that’s the case, no worries — just delete the build  directory, activate the virtual environment with the workon  command, and re-run CMake.

Provided that your CMake output is good to go you can kick off the compilation via:

Note: The -j4 argument is optional and will instruct make  to take advantage of 4 CPU cores. You can adjust the numerical value or leave the argument off completely. It doesn’t happen often, but sometimes race conditions may prevent the compile from finishing — at which point you should execute make  without the flag.

Take a break while the compilation continues, but don’t forget to come back and create symbolic links.

When make  is finished, you should see this:

Figure 6: Compiling OpenCV 4 on macOS has reached 100%. We’re now ready to link OpenCV 4 into our cv environment.

If you’ve reached 100%, then there is one additional command to install OpenCV 4 prior to Step #5:

Step #5: Sym-link OpenCV 4 on macOS to your virtual environment site-packages

Now let’s create what is called a “symbolic link”. We need a link from our cv  virtual environment  site-packages  to our system site-packages  where OpenCV was installed. Effectively, OpenCV will then be “linked” into the virtual environment allowing you to import it into Python scripts as well as the command line interpreter.

First, let’s check the location of the OpenCV bindings — we’ll need the exact location in order to make the link. I encourage you to use tab completion to end up in the right directory rather than copy/pasting the command:

Using the output from that command, we’ll sym-link in OpenCV bindings into the site-packages directory of the cv  Python virtual environment:

Important considerations:

  1. We are creating a symbolic link from the cv  virtual environment Python site-packages  cv2.so  to the global site-packages   cv2.cpython37-darwin.so . Take the time to understand how this works — you might read this article.
  2. Be sure your paths are correct. I recommend tab-completion rather than copy/paste.

I can’t stress this point enough: The cv  Python virtual environment is entirely independent and sequestered from the default Python version on your system. Any Python packages in the global site-packages  directory will not be available to the cv  virtual environment. Similarly, any Python packages installed in site-packages  of cv will not be available to the global install of Python. Keep this in mind when you’re working in your Python virtual environment and it will help avoid a lot of confusion and headaches.

Install imutils

I also recommend that you install my very own imutils package if you’ll be frequently visiting my blog as we use it quite often:

Step #5: Test your macOS + OpenCV 3 install

It is always important to test your OpenCV install to make sure the proper links have been made.

I like to fire up a Python shell in the virtual environment and check that it imports without error and that the version matches my intention:

Figure 7: To test that OpenCV 4 is installed on macOS, fire up Python in your virtual environment and execute cv2.__version__ after importing cv2.

Provided you see no errors and OpenCV 4 is installed, you’re good to go!

Run your first example with your fresh install of OpenCV 4!

If you’re breaking into the field of computer vision with OpenCV, my guess is that you want to run something cool with OpenCV.

Let’s start by building a simple “document scanner” with OpenCV.

I’m not going to review all the code here — you should check out the original post if you’re interested or when you have more time.

To get started, simply scroll to the “Downloads” and grab the source code + images.

From there just enter the following commands to prepare:

As you can see, there are two sample images, a pyimagesearch  module (which needs to be downloaded via the “Downloads” section — it is not pip-installable), and the scan script.

We’ll need one additional library added to our cv  environment: Scikit-image. To install it, simply use pip. While you’re at it, if you didn’t install imutils earlier, go ahead and install it as well:

From there you can execute the following command to give OpenCV 4 a workout:

At the end of each step, you’ll need to press a key — with the window in focus on your desktop.

Sometimes OpenCV’s hides windows under one another, so be sure to drag the OpenCV image windows around to see what is available.

Here’s a screenshot of the last step of document scanning:

Figure 8: Applying step 3 of our document scanner, perspective transform. The original image is on the left and the scanned image on the right.

That was fun!

Learn how the code works by reading the original blog post.

If you’d like to build additional projects with OpenCV 4, just continue to follow my blog!

Troubleshooting and FAQ

In this section, I address some common questions and problems that readers encounter when installing OpenCV 4 on macOS.

Q. Can I run OpenCV 4 with Python 2.7 on macOS?

A. I suggest you stick with Python 3, but if you’re working on legacy projects, I understand that you might want to use Python 2.7. Here is what you need to do:

  • Install Python 2.7 via Homebrew using brew install python2
  • You should pip with 2.7 in Step #3: sudo python get-pip.py  and sudo pip install virtualenv virtualenvwrapper
  • In Step #3, simply create a Python 2.7 environment: mkvirtualenv cv -p python2.7
  • Verify CMake output is using your Python 2.7 virtual environment interpreter in Step #4, Figure 5.

Q. Do I need to run brew install Python? Python seems to already be installed on my Mac!

A. Yes. Python is installed, but you’ll want Brew’s updated Python and plus Brew will put Python in /usr/local/bin  which is separate from your system Python.

Q. When I execute mkvirtualenv  or workon , I encounter a “command not found error”.

A. There a number of reasons why you would be seeing this error message, all of come from to Step #3:

  1. First, make sure you have installed virtualenv  and virtualenvwrapper  properly using the pip  package manager. Verify by running pip freeze , and ensure that you see both virtualenv  and virtualenvwrapper  in the list of installed packages.
  2. Your ~/.bash_profile  file may have mistakes. View the contents of your ~/.bash_profile  file to see the proper export  and source  commands are present (check Step #3 for the commands that should be appended to ~/.bash_profile ).
  3. You may have forgotten to source  your ~/.bash_profile . Make sure you run  source ~/.bash_profile  after editing it to ensure you have access to the mkvirtualenv  and workon  commands.

Q. When I open a new terminal, logout, or reboot my macOS system, I cannot execute the mkvirtualenv  or workon  commands.

A. See #2 from the previous question.

Q. I reached the end, however when I run Python in my terminal and try to import cv2 , I encounter an error. What next?

A. Unfortunately this situation is hard to diagnose without being on your system. Many things could have gone wrong. The most likely point of failure is the symbolic linking step. I suggest you do the following to check the symbolic link:

What you’re looking for is the ->  arrow and that it points to a valid path on your system. If the path is invalid, then you have a sym-link issue that you need to fix. You can correct it by deleting the symlink and trying Step #5 again.

Q. Can I install OpenCV with Brew instead of compiling from source?

A. Beware! The answer is yes, but it if you plan on using virtual environments you’ll still need symbolic links. I’ll do another writeup on the Homebrew method in the future.

Q. Can I install OpenCV with pip into my virtual environment?

A. Yes, but… Stay tuned over the next two weeks for a dedicated blog post demonstrating all you need to know. In short, pip will install a pre-compiled binary. Unfortunately it might not take advantage of all available software on your machine which you’d like OpenCV to be compiled for. You might also have issues with HighGUI, and trust me — you want HighGUI so you can easily work with OpenCV for computer vision development and debugging.

Summary

Today we installed OpenCV4 with Python bindings on your macOS machine.

I’ll be back with future installation tutorials for OpenCV 4 (including one for the Raspberry Pi). If you’re looking for my other, already published OpenCV install tutorials, be sure to refer to this page.

Stay tuned!

To download the source code for today’s tutorial, just enter your email in the form below.

Downloads:

If you would like to download the code and images used in this post, please enter your email address in the form below. Not only will you get a .zip of the code, I’ll also send you a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL! Sound good? If so, enter your email address and I’ll send you the code immediately!

, , , ,

31 Responses to Install OpenCV 4 on macOS

  1. BENYA August 17, 2018 at 6:34 pm #

    It’s nice tutorial that millions euros can’t buy.. Thank you so much for great tutorial.

    • Adrian Rosebrock August 19, 2018 at 8:24 am #

      Thanks Benya!

  2. Robert Franks August 18, 2018 at 8:38 pm #

    Hi Adrian- I got an error during make-


    initialize a variable of type ‘char *’ with an rvalue of type
    ‘const char *’
    char* str = PyString_AsString(obj);
    ^ ~~~~~~~~~~~~~~~~~~~~~~

    Any Ideas?

    • Adrian Rosebrock August 19, 2018 at 8:26 am #

      Try the following commit IDs:

      • OpenCV: 76eb38976103c86610f73d87e46b7cb5a74f0017
      • Contrib: 9adf7a58a02be9db1152b9c7ba5fc2404a7925ed

      Check out those IDs using git, delete your “build” directory, and then start the compile again.

      • Paco Brevers August 20, 2018 at 6:35 am #

        Solved =)

        • Adrian Rosebrock August 20, 2018 at 2:39 pm #

          Awesome, I’m glad that worked!

      • Florian L August 20, 2018 at 9:35 am #

        The build completed successfully with these two commit ids. Thanks!

        • Adrian Rosebrock August 20, 2018 at 2:40 pm #

          Thanks for confirming, Florian 🙂

      • Robert Franks August 20, 2018 at 6:26 pm #

        Worked for me as well, thanks

        • Adrian Rosebrock August 22, 2018 at 9:47 am #

          Awesome, congrats on getting OpenCV 4 installed!

      • Tom August 20, 2018 at 8:03 pm #

        Hi Adrian — that commit ID for opencv_contrib doesn’t exist?

        $(opencv_contrib)> git checkout 9adf7a58a02be9db1152b9c7ba5fc2404a7925ed
        fatal: reference is not a tree: 9adf7a58a02be9db1152b9c7ba5fc2404a7925ed

        • Adrian Rosebrock August 22, 2018 at 9:48 am #

          Hey Tom — I would suggest trying again. Other readers are reporting success with that specific commit.

      • Allan Dickson August 29, 2018 at 9:02 am #

        That worked for me too!

  3. PAULO GONCALVES August 19, 2018 at 10:01 pm #

    Dear Adrian,
    thank you very much,

    I am having an issue when to make opencv 4.

    the error appear:
    can you help?


    char* str = PyString_AsString(obj);
    ^ ~~~~~~~~~~~~~~~~~~~~~~
    1 error generated.

    I have python 3.7 on my workon py3cv4

    thanks, Paulo.

    • PAULO GONCALVES August 20, 2018 at 9:26 am #

      thank you Adrian,
      your previous answers worked ok.

      OpenCV: 76eb38976103c86610f73d87e46b7cb5a74f0017
      Contrib: 9adf7a58a02be9db1152b9c7ba5fc2404a7925ed
      Check out those IDs using git, delete your “build” directory, and then start the compile again.

      best,
      Paulo.

  4. M Johannessen August 20, 2018 at 4:04 pm #

    I’m fine to the point of making the symlinks at

    $ ls /usr/local/lib/python3.7/site-packages/cv2.cpython-37m-darwin.so

    I have the file cv2.cpython-36m-darwin.so at $ ls /usr/local/lib/python3.6/site-packages/

    but not in the /usr/local/lib/python3.7/site-packages/ directory.

    I have python 3.7 installed (using brew) at /usr/local/Cellar/python/3.7.0

    Where does cv2.cpython-37m-darwin.so get installed?

    • Adrian Rosebrock August 22, 2018 at 9:50 am #

      If you’re using Python 3.7 I’m not sure why you would have a file named “cv2.cpython-36m-darwin.so” in your Python 3.7 site-packages directory. My guess is that your paths are incorrect. Go back and double-check them.

  5. Nitin August 20, 2018 at 11:08 pm #

    I did not create a virtual env but proceeded with the steps excluding that. I can’t see cv2 in my site-packages and I have an anaconda version of python.

    • Adrian Rosebrock August 22, 2018 at 9:46 am #

      If you’re using Anaconda your PYTHON3_LIBRARY, PYTHON3_INCLUDE_DIR, and PYTHON3_EXECUTABLE paths will need to be updated. You’ll need to manually verify them yourself.

  6. Andrew Baker August 21, 2018 at 3:19 am #

    Hi Adrian, I built mine successfully using python 3.6.5. However the built cv2.cpython-36m-darwin.so file ended up in a python3 folder located within the opencv build folder. I could have created the link from there, but just ended up copying the file into the usr/local/lib/python3.6/site-packages folder.

    • Adrian Rosebrock August 22, 2018 at 9:43 am #

      Awesome, congrats on getting OpenCV 4 installed on your macOS machine, Andrew!

  7. Jesudas Fernandes August 22, 2018 at 3:09 am #

    thanks Adrian,

    For publishing this blog, and giving us head start with Open CV 4.
    The commit ids provided in the QnA section was required to overcome the build error.

    • Adrian Rosebrock August 22, 2018 at 9:22 am #

      Thank you for confirming, Jesudas! 🙂 And congrats on getting OpenCV 4 installed on your machine.

  8. Ashutosh Sharma August 23, 2018 at 11:15 am #

    Can you please help me setup caffe in my mac please!

  9. Ashutosh Sharma August 23, 2018 at 1:24 pm #

    Billions of Thanks Adrian for helping in setting up openCV 4 on python 3.7

    • Adrian Rosebrock August 24, 2018 at 8:37 am #

      Thanks Ashutosh! I’m glad you were able to get OpenCV 4 installed 🙂

  10. Adebiyi Abdurrahman August 26, 2018 at 2:14 pm #

    For the love of God, please adhere to the “make -j4” vs “make”
    advise by Adrian while compiling the opencv4. Miss it and you can be on a one way ticket to a hellish install.

  11. Bob September 7, 2018 at 3:20 pm #

    No matter which commit I use (head, 76eb38976103c86610f73d87e46b7cb5a74f0017, or 46def2fdc194ebd43a703845013bc54c59ce9d75) I get errors on the CMake stage of the installation.

    First one is:
    error “__POPCNT__ is not defined by compiler”

    Not sure how many after that are due to the initial one blowing up the compile process.

    This is OS X 10.13.6, python version is 3.7 via homebrew.

    Any possible suggestions for why it’s dying there?

    • Adrian Rosebrock September 11, 2018 at 8:26 am #

      Hey Bob — I’m sorry to hear about the error. Unfortunately, I’m not sure what the exact issue is. I imagine it’s due to a development release of OpenCV 4 and not the official release. I’m sure the problem will be cleared up for the final release later this year 🙂

  12. Jean-Christophe Yacono September 7, 2018 at 5:54 pm #

    Hi Adrien, No so far from the end (cmake -D CMAKE_BUILD_TYPE=RELEASE \), I get that alert : -bash: cmake: command not found

    any help?

    • Adrian Rosebrock September 11, 2018 at 8:25 am #

      If the “cmake” command is not installed I think you may have forgotten to either:

      1. Install Xcode
      2. And/or run sudo xcode-select --install

      Go back to Step #1 and verify you’ve ran those commands.

Quick Note on Comments

Please note that all comments on the PyImageSearch blog are hand-moderated by me. By moderating each comment on the blog I can ensure (1) I interact with and respond to as many readers as possible and (2) the PyImageSearch blog is kept free of spam.

Typically, I only moderate comments every 48-72 hours; however, I just got married and am currently on my honeymoon with my wife until early October. Please feel free to submit comments of course! Just keep in mind that I will be unavailable to respond until then. For faster interaction and response times, you should join the PyImageSearch Gurus course which includes private community forums.

I appreciate your patience and thank you being a PyImageSearch reader! I will see you when I get back.

Leave a Reply