亲证可用:http://www.jianshu.com/p/11959977589a
- Mac OS X 10.1
- Xcode 7.2(7C68)
- OpenCV 2.4.13
Mac OS10.11
![](http://upload-images.jianshu.io/upload_images/2336041-8ad32ff499c82cc0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
下载OpenCV后,cd进入指定目录,使用unzip命令解压
请提前安装Homebrew命令
先安装cmake工具然后cd进入解压后的文件夹
$ brew install cmake
$ mkdir release
$ cd release
$ cmake -G "Unix Makefiles" .. $ make $ sudo make install
如果没有意外,OpenCV已经安装成功。其中,lib文件存放在“/usr/local/lib”文件夹,h文件存放在“/usr/local/include”。
Terminal下调用OpenCV
进入开发工作目录,新建测试文件DisplayImage.cpp
$ vi DisplayImage.cpp
并插入以下代码:
#include <cv.h>
#include <highgui.h> using namespace cv; int main( int argc, char** argv ) { Mat image; image = imread( argv[1], 1 ); if( argc != 2 || !image.data ) { printf( "No image data \n" ); return -1; } namedWindow( "Display Image", CV_WINDOW_AUTOSIZE ); imshow( "Display Image", image ); waitKey(0); return 0; }
新建配置文件CMakeLists.txt ,用于声称makefile文件,如下:
project( DisplayImage )
find_package( OpenCV REQUIRED ) add_executable( DisplayImage DisplayImage ) target_link_libraries( DisplayImage ${OpenCV_LIBS} )
编译两个文件
cd <DisplayImage_directory> //进入DisplayImage.cpp文件所在目录
cmake .
make
运行编译好的结果(turin.jpg文件与DisplayImage在同一个目录下)
./DisplayImage turin.jpg
看到目标图片,美丽可爱的Turin就表示成功啦~当然这只是第一步,除了C++代码还要学会编写Makefile(CMake)文件哦
Xcode调用OpenCV库
创建一个空的command line工程
![](http://upload-images.jianshu.io/upload_images/2336041-0f9c251fac19aebd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
选择合适的名字,然后进入主页面,并将main文件替换成如下代码:
![](http://upload-images.jianshu.io/upload_images/2336041-08e1722bea7106c0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
#include <iostream>
#include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv/cvaux.hpp> #include <fstream> using namespace std; #define BYTE unsigned char int main(int argc, const char * argv[]) { //这个地方的目录需要改成自己的 IplImage* img = cvLoadImage("/Users/Kingsley/Desktop/turin.jpg", 1); //NSLog(img); //create a window to display the image cvNamedWindow("picture", 1); //show the image in the window cvShowImage("picture", img); //wait for the user to hit a key cvWaitKey(0); //delete the image and window cvReleaseImage(&img); cvDestroyWindow("picture"); return 0; }
添加lib文件:右键点击工程名,选择“Add files to..”,使用快捷键“Command+Shift+G” 在弹出的Go to the Folder框里面输入:/usr/local/lib,全选该文件夹下的全部dylib文件,添加至工程。
添加lib文件查找支持: 双击工程名文件,进入“Build Settings”选项卡,在“Library Search Paths”栏(可以使用搜索功能)中输入“/usr/local/lib”
![](http://upload-images.jianshu.io/upload_images/2336041-bcdac6a3b4ac719a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
添加头文件:点击工程名文件,进入“Build Settings”选项卡,在“Header Search Paths”栏中输入:“/usr/local/include /usr/local/include/opencv”
![](http://upload-images.jianshu.io/upload_images/2336041-7b03e820e2497483.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)