Installation of OpenCV with Python on MacOS Sierra

Denis Hsieh
Jan 18, 2017 · 3 min read

小弟的研究方向是關於影像處理,更精確的說是電腦視覺(Computer Vision)方面,提到CV library的集大成就是OpenCV了,但OpenCV是由C++編寫,很多人會用更方便的Python來操作OpenCV。於是乎為了記錄安裝的步驟與過程,本篇文章就誕生啦!

上網找了許多資料,發現要使用OpenCV — Python binding好像都要自行編譯,而沒有現成的套件可以安裝,目前還不太懂為什麼。

找到了幾篇相關的文章但是很多都與目前使用的環境有所出入且在這種情況下,安裝過程中通常會遇到複雜難解的奇怪問題。其中兩篇較完整的教學在PyImageSearch[1]還有Medium[2]上,但是我在安裝過程中仍然上遇到了一些問題,例如在[1]中,因為我原先安裝的Python來自安裝包,與使用Homebrew安裝的路徑不同,產生了問題(e.g. 在使用virtualenvwrapper的時候也無法順利啟動);在[2]中,雖然有遇到問題但還是順利解決並安裝成功了,以下會詳述此篇教學的安裝過程並且融合我所遇到的問題與解法。

首先,為了符合教學裡的環境設定,先把自己的Python環境打掉重練,使用Pyenv安裝Python,詳細可以參考我另一篇文章 — MacOS上的Python路徑問題&安裝方法[3]。

安裝Pyenv過程中,我犯了一個錯誤

# Add the following to your ~/.bash_profile
# We want to load pyenv every time we open a new shell
if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi

因為安裝說明要把上述codeblock內的第三行指令新增入“~/.bash_profile”,但我忘了已經將shell預設為zsh,所以應該是要把該行指令加入“~/.zshrc”,導致後續教學中[2]所提供的shell script無法正確操作pip去安裝套件因為路徑裡找不到Python的位置,後續編譯步驟就會失敗。

接著,正確安裝並設定完Pyenv後,我將原教學中MacOS版的shell script做了些許修改,請參考DenisHsieh/opencv_installation_scripts[4]。

最後,只要先裝好Homebrew,後續的Pyenv、Python及相關套件安裝及編譯OpenCV全部交給script自動化處理。

如果想知道OpenCV與Python如何交互運作可以參考OpenCV-Python Bindings[5]。

[1] PyImageSearch — macOS: Install OpenCV 3 and Python 3.5

[2] Medium — Python 3.6, OpenCV 3.2, and PyEnv on macOS Sierra

[3] Denix Daily — MacOS上的Python路徑問題&安裝方法

[4] Github — DenisHsieh/opencv_installation_scripts

[5] OpenCV Documentation — OpenCV-Python Bindings

Denis Brain

The Way to Become a Software Engineer | 邁向軟體工程師之路

Denis Hsieh

Written by

Denis Brain

The Way to Become a Software Engineer | 邁向軟體工程師之路

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade