Kaushil Ruparelia Kaushil Ruparelia - 7 months ago 764
Swift Question

Using OpenCV in Swift iOS

After adding the OpenCV 2 framework in my xcode project, I tried searching for samlpes or tutorials for integration with swift.

Are there any good tutorials for the same?

Answer

OpenCV is a framework written in C++. Apple's reference tell us that

You cannot import C++ code directly into Swift. Instead, create an Objective-C or C wrapper for C++ code.

so you cannot directly import and use OpenCV in a swift project, but this is actually not bad at all because you (need) continue to use the C++ syntax of the framework which is pretty well documented all over the net.

So how do you proceed?

  1. Create a new Objective-C++ class (.h, .mm)

OpenCVWrapper.h

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@interface OpenCVWrapper : NSObject

    + (UIImage *)processImageWithOpenCV:(UIImage*)inputImage;

@end

OpenCVWrapper.mm (you'll need to add a UIImage+OpenCV category to the project as well)

#include "OpenCVWrapper.h"
#import "UIImage+OpenCV.h"

#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

@implementation OpenCVWrapper : NSObject

    + (UIImage *)processImageWithOpenCV:(UIImage*)inputImage {
        Mat mat = [inputImage CVMat];

        // do your processing here
        ...

        return [UIImage imageWithCVMat:mat];
    }

@end
  1. Update the Bridging-Header importing our newly created wrapper (#import "OpenCVWrapper.h")

  2. Use your wrapper in your Swift files

    let image = UIImage(named: "image.jpeg")
    let processedImage = OpenCVWrapper.processImageWithOpenCV(image)