Title: macOS for deep learning with Python, TensorFlow, and Keras - PyImageSearch

URL Source: https://pyimagesearch.com/2017/09/29/macos-for-deep-learning-with-python-tensorflow-and-keras/

Published Time: 2017-09-29T14:00:43+00:00

Markdown Content:
![Image 1](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20315'%3E%3C/svg%3E)

In today’s tutorial, I’ll demonstrate how you can configure your macOS system for deep learning using Python, TensorFlow, and Keras.

This tutorial is the final part of a series on configuring your development environment for deep learning. I created these tutorials to accompany my new book, [_Deep Learning for Computer Vision with Python_](https://pyimagesearch.com/deep-learning-computer-vision-python-book/); however, you can use these instructions to configure your system _regardless_ if you bought my book or not.

In case you’re on the wrong page (or you don’t have macOS), take a look at the other deep learning development environment tutorials in this series:

*   [Your deep learning + Python Ubuntu virtual machine](https://pyimagesearch.com/2017/09/22/deep-learning-python-ubuntu-virtual-machine/)
*   [Pre-configured Amazon AWS deep learning AMI with Python](https://pyimagesearch.com/2017/09/20/pre-configured-amazon-aws-deep-learning-ami-with-python/)
*   [Configuring Ubuntu for deep learning with Python](https://pyimagesearch.com/2017/09/25/configuring-ubuntu-for-deep-learning-with-python/) (CPU _only_)
*   [Setting up Ubuntu 16.04 + CUDA + GPU for deep learning with Python](https://pyimagesearch.com/2017/09/27/setting-up-ubuntu-16-04-cuda-gpu-for-deep-learning-with-python/)
*   macOS for deep learning with Python, TensorFlow, and Keras (this post)

**To learn how to configure macOS for deep learning and computer vision with Python, _just keep reading_.**

As you get acclimated in the deep learning domain, you’ll want to perform many experiments to hone your skills and even to solve real-world problems.

You’ll find that for experiments in the most chapters inside the _Starter Bundle_ and half the chapters in the _Practitioner Bundle_ can be executed on your CPU. Readers of the _ImageNet Bundle_ will need a GPU machine in order to perform the more advanced experiments.

I definitely don’t recommend churning through large datasets and deep neural networks on your laptop, but like I said, for small experiments it is just fine.

Today, I’ll walk you through the steps to configure your Mac for deep learning.

First, we’ll install Xcode and Homebrew (a package manager). From there we will create a virtual environment called `dl4cv` and install OpenCV, TensorFlow, and Keras into the environment.

Let’s get started.

### Step #1: Install Xcode

For starters, you’ll need to get Xcode from the Apple App Store and install it. Don’t worry, it is 100% free.

[![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20510'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2016/11/sierra_xcode_app_store.jpg)

**Figure 1:** Selecting Xcode from the Apple App Store.

From there, open a terminal and execute the following command to accept the developer license:

$ sudo xcodebuild -license

The next step is to install Apple command line tools:

$ sudo xcode-select --install

[![Image 3](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20539%20402'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2017/09/dl4cv_macos_license.png)

**Figure 2:** Accepting the Xcode license.

### Step #2: Install Homebrew

Homebrew (also known as Brew), is a package manager for macOS. You may already have it on your system, but if you don’t you will want to perform the actions in this section.

First we’ll install Homebrew by copying and pasting the **entire** command into your terminal:

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Next we’ll update our package definitions:

$ brew update

Followed by updating your `~/.bash_profile` using the `nano` terminal editor (any other editor should do the trick as well):

$ nano ~/.bash\_profile

Add the following lines to the file:

\# Homebrew
export PATH=/usr/local/bin:$PATH

[![Image 4](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20530%20395'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2017/09/dl4cv_macos_bashprofile_homebrew.png)

**Figure 3:** Changing _~/.bash\_profile_ to accommodate Homebrew.

Next, simply reload your `~/.bash_profile` (this happens automatically when a new terminal is opened):

$ source ~/.bash\_profile

Now that Brew is ready to go, let’s get Python 3 installed.

### Step #3: Install Homebrew Python 3 for macOS

This step is actually very easy, but I want to clear up some possible confusion first.

macOS comes with Python installed; however we will be installing a non-system Python using Brew. While you _could_ use your system Python, it is actually _**strongly discouraged**_. Therefore, don’t skip this step — it is very important to your successful install.

To install Python 3 with Homebrew, simply execute this command:

$ brew install python3

Before continuing you’ll want to verify that your Python 3 installation is Homebrew’s rather than the macOS system’s:

$ which python3
/usr/local/bin/python3
$ which pip3
/usr/local/bin/pip3

Ensure that you see “`local` ” in each path. If you don’t see this output, then you aren’t using Homebrew’s install of Python 3.

[![Image 5](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20531%20388'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2017/09/dl4cv_macos_which_python3_pip3.png)

**Figure 4:** Executing _which python3_ and _which pip3_ to ensure that you are using the Homebrew version of each rather than the system version.

Assuming your Python 3 install worked, let’s continue on to **Step #4**.

### Step #4: Create your Python virtual environment

As I’ve stated in [other install guides on this site](https://pyimagesearch.com/opencv-tutorials-resources-guides/), virtual environments are definitely the way to go when working with Python, enabling you to accommodate different versions in sandboxed environments.

In other words, there is less of a chance that you’ll do something that is a pain in the ass to fix. If you mess up an environment, you can simply delete the environment and rebuild it.

Let’s install [virtualenv](https://virtualenv.pypa.io/en/latest/) and [virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/) via `pip` :

$ pip3 install virtualenv virtualenvwrapper

From there, we’ll update our `~/.bash_profile` again:

$ nano ~/.bash\_profile

Where we’ll add the following lines to the file:

\# virtualenv and virtualenvwrapper
export VIRTUALENVWRAPPER\_PYTHON=/usr/local/bin/python3
source /usr/local/bin/virtualenvwrapper.sh

[![Image 6](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20532%20396'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2017/09/dl4cv_macos_bash_profile_virtualenv.png)

**Figure 5:** The bottom of our _~/.bash\_profile_ should contain these lines for virtualenv and virtualenvwrapper.

Followed by reloading the file:

$ source ~/.bash\_profile

#### Creating the ‘dl4cv’ environment

The `dl4cv` environment will house all of our software for performing experiments associated with [my book](https://pyimagesearch.com/deep-learning-computer-vision-python-book/). You can easily name the environment whatever you want, but from here on we’ll be referring to it as `dl4cv` .

To create the dl4cv environment with **Python 3** simply enter the following command:

$ mkvirtualenv dl4cv -p python3

After Python 3 and supporting scripts are installed into the new environment, you should actually be _inside_ the environment. This is denoted by a ‘`(dl4cv)` ‘ at the beginning of your bash prompt as shown in the figure below:

[![Image 7](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20530%20391'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2017/09/dl4cv_macos_dl4cv.png)

**Figure 6:** The _(dl4cv)_ in the bash prompt signifies that we are working inside the _dl4cv_ virtual environment. If you don’t see this, then execute _workon dl4cv_ to activate the environment.

If you do not see the modified bash prompt then you can enter the following command at any time to enter the environment at any time:

$ workon dl4cv

The only Python dependency required by OpenCV is NumPy, which we can install below:

$ pip install numpy

That’s it as far as creating a virtual environment and installing NumPy. Let’s continue to **Step #5**.

### Step #5: Install OpenCV prerequisites using Homebrew

The following tools need to be installed for compilation, image I/O, and optimization:

$ brew install cmake pkg-config wget
$ brew install jpeg libpng libtiff openexr
$ brew install eigen tbb

After those packages are installed we’re ready to install OpenCV.

### Step #6: Compile and Install OpenCV

First, let’s download the source code:

$ cd ~
$ wget -O opencv.zip https://github.com/opencv/opencv/archive/3.3.0.zip
$ wget -O opencv\_contrib.zip https://github.com/opencv/opencv\_contrib/archive/3.3.0.zip

Then unpack the archives:

$ unzip opencv.zip
$ unzip opencv\_contrib.zip

Followed by configuring the build with CMake (it is very important that you copy the CMake command _**exactly**_ as it appears here, taking care to copy and past the _**entire**_ command; I would suggest clicking the _“<=>”_ button in the toolbar below to expand the entire command):

$ cd ~/opencv-3.3.0/
$ mkdir build
$ cd build
$ cmake -D CMAKE\_BUILD\_TYPE=RELEASE \\
    -D CMAKE\_INSTALL\_PREFIX=/usr/local \\
    -D OPENCV\_EXTRA\_MODULES\_PATH=~/opencv\_contrib-3.3.0/modules \\
    -D PYTHON3\_LIBRARY=\`python -c 'import subprocess ; import sys ; s = subprocess.check\_output("python-config --configdir", shell=True).decode("utf-8").strip() ; (M, m) = sys.version\_info\[:2\] ; print("{}/libpython{}.{}.dylib".format(s, M, m))'\` \\
    -D PYTHON3\_INCLUDE\_DIR=\`python -c 'import distutils.sysconfig as s; print(s.get\_python\_inc())'\` \\
    -D PYTHON3\_EXECUTABLE=$VIRTUAL\_ENV/bin/python \\
    -D BUILD\_opencv\_python2=OFF \\
    -D BUILD\_opencv\_python3=ON \\
    -D INSTALL\_PYTHON\_EXAMPLES=ON \\
    -D INSTALL\_C\_EXAMPLES=OFF \\
    -D BUILD\_EXAMPLES=ON ..

_**Note:** For the above CMake command, I spent considerable time creating, testing, and refactoring it. 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.  
_

Your output should be similar to the screenshot below which ensures that the correct Python 3 binary/library and NumPy version are utilized:

[![Image 8](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20529%20392'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2017/09/dl4cv_macos_cmake_python_numpy.png)

**Figure 7:** The OpenCV CMake output that ensures the correct Python 3 and NumPy will be used for compiling.

Then we’re ready to perform the compilation compile OpenCV:

$ make -j4

_**Note:** The number ‘4’ above specifies that we have 4 cores/processors for compiling. If you have a different number of processors you can update the `-j` switch. For only one core/processor simply just use the `make` command (from the build directory enter `make clean` prior to retrying if your build failed or got stuck)._

From there you can install OpenCV:

$ sudo make install

After installing it is necessary to sym-link the `cv2.so` file into the `dl4cv` virtual environment:

$ cd ~/.virtualenvs/dl4cv/lib/python3.6/site-packages/
$ ln -s /usr/local/lib/python3.6/site-packages/cv2.cpython-36m-darwin.so cv2.so
$ cd ~

Finally, we can test out the install:

$ python
>>> import cv2
>>> cv2.\_\_version\_\_
'3.3.0'

[![Image 9](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20522%20385'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2017/09/dl4cv_macos_cv2_version.png)

**Figure 8:** OpenCV 3.3 has been installed and linked as is shown by the successful import and display of the version.

If your output properly shows the version of OpenCV that you installed, then you’re ready to go on to **Step #7** where we will install the Keras deep learning library.

### Step #7: Install Keras

Before beginning this step, ensure you have activated the `dl4cv` virtualenv. If you aren’t in the environment, simply execute:

$ workon dl4cv

Then, using `pip` , install the required Python computer vision, image processing, and machine learning libraries:

$ pip install scipy pillow
$ pip install imutils h5py requests progressbar2
$ pip install scikit-learn scikit-image

Next install matplotlib and **update the rendering backend**:

$ pip install matplotlib
$ touch ~/.matplotlib/matplotlibrc
$ echo "backend: TkAgg" >> ~/.matplotlib/matplotlibrc

Then, install TensorFlow:

$ pip install tensorflow

Followed by keras:

$ pip install keras

To verify that Keras is installed properly we can import it and check for errors:

$ python
>>> import keras
Using TensorFlow backend.
>>>

Keras should be imported with no errors, while stating that TensorFlow is being utilized as the backend.

[![Image 10](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20528%20390'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2017/09/dl4cv_macos_keras_installed.png)

**Figure 9:** Keras is successfully installed into the _dl4cv_ virtual environment.

At this point, you can familiarize yourself with the `~/.keras/keras.json` file:

{
	"image\_data\_format": "channels\_last",
	"backend": "tensorflow",
	"epsilon": 1e-07,
	"floatx": "float32"
}

Ensure that the `image_data_format`  is set to `channels_last`  and that the `backend`  is set to `tensorflow` .

_**Congratulations!**_ You’re now ready to go. If you didn’t open up a beer or coffee during the installation process, now is the time. It’s also the time to find a comfortable spot to read [_Deep Learning for Computer Vision with Python_](https://pyimagesearch.com/deep-learning-computer-vision-python-book/).

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 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:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ 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_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

Summary
-------

In today’s post, we configured our macOS box for computer vision and deep learning. The main pieces of software included Python 3, OpenCV, TensorFlow, and Keras accompanied by dependencies and installation/compilation tools.

As you can see, utilizing Homebrew, pip, and virtualenv + virtualenvwrapper made this install rather easy. I spent quite a bit of time creating and testing  the CMake command which should work easily on your computer. Be sure to give it a try.

If you encountered any problems along the way, leave a comment in the form below.

If you would like to put your newly configured macOS deep learning environment to good use, I would highly suggest you take a look at my new book, [_Deep Learning for Computer Vision with Python_](https://pyimagesearch.com/deep-learning-computer-vision-python-book/).

Regardless if you’re **new to deep learning** or **already a seasoned practitioner**, the book has content to help you reach deep learning mastery — [take a look here](https://pyimagesearch.com/deep-learning-computer-vision-python-book/).

![Image 11](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### 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.