Integrate OpenCV in IOS (part 1)

Sunny Kumar
3 min readNov 1, 2022

--

Imagine a situation where you have to do image manipulation in an IOS based app. well, i will be taking you through the process of how you can integrate openCV lib in swift for an IOS application.

Create a sample ios Project.

Here is the link to download openCV lib for IOS. Download the most recent version. It will be a zip file, unzip it and drag it to your Swift project.

drag unzipped open cv to here.

since openCv is written is C++ so next step is to create a link between swift and C++ code. You can simple think of this technique as calling a C++ code from a swift code, interesting isn’t it.

Next, we will create two files “openCvWrapper.h” and “openCvWrapper.mm” . Go to new file-> select cocoa touch class -> subclass as NSObject and language as Objective-C. (see image below)

once you click “Next” , it will create two file with extension “.h” and “.m”. Change extension of .m to .mm. This is very important as it will instruct compiler about the C++ used in code.

copy the below line in your .h file.

#import <Foundation/Foundation.h>#import "OpenCVWrapper.h"NS_ASSUME_NONNULL_BEGIN@endNS_ASSUME_NONNULL_END

copy the below code in your .mm file.

#import <Foundation/Foundation.h>#import "OpenCVWrapper.h"NS_ASSUME_NONNULL_BEGIN
@endNS_ASSUME_NONNULL_END

Till now you have created , the files where you will write your C++ code using OpenCv lib.Now, you open your bridging header and add below line to it.

#import "OpenCVWrapper.h"

well done, now you are all set use opencv in your ios code.

Just to visualize, your .h file will contain method name and definition and your .mm file will contain method implementation.

open your .h file and add following code.

#import <Foundation/Foundation.h>#import "OpenCVWrapper.h"NS_ASSUME_NONNULL_BEGIN@interface OpenCvWrapper : NSObject+ (NSString *)getOpenCVVersion;@endNS_ASSUME_NONNULL_END

Here, “+ (NSString *)getOpenCVVersion”, is the method name, we will add its implementation to .mm file. As, name suggest it will give you version of current Opencv lib.

Now, open .mm file and and add implementation of the method. Your .mm file should look like this.

#import <opencv2/opencv.hpp>#import "OpenCvWrapper.h"@implementation OpenCvWrapper+ (NSString *)getOpenCVVersion{return [NSString stringWithFormat:@"OpenCV Version %s",  CV_VERSION];}@end

Now , only step remaining is calling your function from Swift code.

Open viewController and inside call the function as follow.

var version = OpenCvWrapper.getOpenCVVersion().

you can clone the code from here :-

git clone https://bitbucket.org/sunnykumar1516/opencvintegration.git

This a series of Opencv tutorials. I will keep adding more complexities in future. Thanks. 😊

--

--

Sunny Kumar

Loves technology . Combining AI and AR to create meaningful solutions.