OpenCV:mac上安裝和配置
一、環境準備
使用HomeBrew安裝cmake
brew install cmake
獲取OpenCV原始碼
- 可以到官方下載頁下載穩定版本 ofollow,noindex">https://opencv.org/releases.html
- 從git倉庫克隆
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
構建OpenCV
- 在原始碼目錄中建立一個臨時目錄,這裡會存放一下cmake編譯生成的檔案
cd~ / opencvmkdir build
- 配置
cd buildcmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local ..
- 構建安裝
make -j7#並行執行7個作業
sudo make install
至此OpenCV在MAC上算安裝完畢了。
二、測試
安裝好 OpenCV 後,在 /usr/local/lib 下能看到這樣的檔案這說明已經安裝成功了

lib.png
開啟Xcode,新建一個command line工程:注意語言選擇C++。
接下來先來配置xcode再來寫程式碼。 最左邊選中工程,然後右邊選中Targets,再BuildSettings下,右邊搜尋框裡輸入search,找到Search Paths設定項。在Header Search Paths裡輸入:/usr/local/include 在Library Search Paths裡輸入:/usr/local/lib

xcode1.png
接著在Build Phases裡找到Link Binary With Libraries,點選+號 ,選擇add other,然後按下/鍵,輸入lib的路徑/usr/local/lib,然後就是選擇OpenCV的庫了,用哪個新增哪個,
在main.cpp裡輸入以下內容,實現顯示一張照片及顯示灰度化後的:
#include <iostream> #include <opencv2/opencv.hpp> using namespace cv; using std::string; int main(int argc, const char * argv[]) { string path = "/Users/*/Desktop/test.jpg"; Mat image = imread(path); namedWindow("origin"); imshow("origin", image); Mat gray; cvtColor(image, gray, COLOR_RGBA2GRAY); namedWindow("gray"); imshow("gray", gray); waitKey(0); return 0; }
執行效果如下:

result.png