Thursday, December 25, 2014

How to Add OpenCV to XCode

In this tutorial, I am going to convert an image called StBernard.jpg (a dog) to grayscale then add Gaussian Blur.  And in the process learn how to add OpenCV to Xcode. It is modified from:

https://github.com/Itseez/opencv_for_ios_book_samples

by Alexander Shishkov. Credits to Alexander for his original code.
However, you should read Alexander's book Instant OpenCV For iOS for the detailed explanation.

Alexander's original code may not work on XCode6.1.1, hence this tutorial. Hope it helps someone.


Note that my platform is:

Mavericks, Xcode 6.1.1 and iOS 8.1

Download openCV framework for iOS:

http://opencv.org/downloads.html

Select Version 2.4.10 - OpenCV for iOS

Then create a new Xcode project, single view. call it InstantOpenCV, or anything you like.
Then add these 3 frameworks:



Then, in the storyboard, add a UIImageView:


Then, in Build Settings, AppleLLVM6.0 Language, set Compile Source As: Objective-C++ :


Hookup your IBOutlet to the UIImageView, then create imageView variable,  and also add the opencv header files opencv2/opencv.hpp and opencv2/highgui/ios.h.  Your ViewController.h should look like this:

//
//  ViewController.h
//  InstantOpenCv
//
//  Created by Paul Chin on 12/25/14.
//  Copyright (c) 2014 Paul Chin. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <opencv2/opencv.hpp>
#import <opencv2/highgui/ios.h>

@interface ViewController : UIViewController{
    cv::Mat cvImage;
}
@property (weaknonatomicIBOutlet UIImageView *imageView;


@end



Then add code to ViewController.m:

//
//  ViewController.m
//  InstantOpenCv
//
//  Created by Paul Chin on 12/25/14.
//  Copyright (c) 2014 Paul Chin. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //self.imageView.image=[UIImage imageNamed:@"StBernard.jpg"];
    
    UIImage *image = [UIImage imageNamed:@"StBernard.jpg"];
    UIImageToMat(image, cvImage);
    if(!cvImage.empty()){
        using namespace cv;
        Mat gray;
        cvtColor(cvImage, gray, CV_RGB2GRAY);//convert to single channel
        GaussianBlur(gray, gray, cvSize(55),1.2,1.2);//remove small details
        self.imageView.image=MatToUIImage(gray);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

@end


Notice I use StBernard.jpg as the image, but you can use your own. Just add it to your SupportingFiles folder. Right click Supporting files folder, then select Add Files to:


Then, run your app in iOS Simulator:


Note that I'm using Adaptive Layout:



The constraints are as shown on Size Inspector on right above.




1 comment: