Swift + OpenCV 2
前回の続きです。
Objective-C
File>New>FileでObjective-Cのファイルを追加すると、実装ファイルの他に通常の「クラス名.h」ではなく「プロジェクト名-Bridging-Header.h」というファイルが作成されます。
Swiftと連携するためのファイルとのことですが、記述する内容は変更ありません。
swImageViewer-Bridging-Header.h
#import < Foundation / Foundation.h > #import < UIKit / UIKit.h > @interface ImageController : NSObject - (void)initOpenCv:(UIImage *)imgSource; - (UIImage *)getImgColor; - (UIImage *)getImgGray; - (UIImage *)getImgThreshold; - (UIImage *)getImgSobel; @end
ImageController.mm
実装ファイルも同じですね。viewDidLoadで実行していた画像の操作を、initOpenCvで行っています。
#import "swImageViewer-Bridging-Header.h" #import < opencv2 / opencv.hpp > #import "opencv2 / highgui / ios.h" @interface ImageController() @property (strong, nonatomic) UIImage *imgColor; @property (strong, nonatomic) UIImage *imgGray; @property (strong, nonatomic) UIImage *imgThreshold; @property (strong, nonatomic) UIImage *imgSobel; @end @implementation ImageController - (void)initOpenCv:(UIImage *)imgSource { cv::Mat matColor; // UIImageをcv::Matに変換する UIImageToMat(imgSource, matColor); // cv::MatをUIImageに変換 _imgColor = MatToUIImage(matColor); // グレイスケール cv::Mat matGray; cv::cvtColor(matColor, matGray, CV_BGR2GRAY); // cv::MatをUIImageに変換 _imgGray = MatToUIImage(matGray); // 白黒の2値化処理 cv::Mat matThreshold; cv::threshold(matGray, matThreshold, 0, 255, cv::THRESH_BINARY|cv::THRESH_OTSU); // cv::MatをUIImageに変換 _imgThreshold = MatToUIImage(matThreshold); // Sobelフィルタによる輪郭検出 cv::Mat matSobel; cv::Sobel(matThreshold, matSobel, CV_16S, 1, 0, 3); cv::convertScaleAbs(matSobel, matSobel); // cv::MatをUIImageに変換 _imgSobel = MatToUIImage(matSobel); } - (UIImage *)getImgColor { return _imgColor; } - (UIImage *)getImgGray { return _imgGray; } - (UIImage *)getImgThreshold { return _imgThreshold; } - (UIImage *)getImgSobel { return _imgSobel; } @end
参考
終わりに
現状思ったよりもObjective-Cと共通するところが多く、Swiftに書き換えるときの手助けになっている気がします。
ただ、OpenCVやopenFrameworksなどCやC++を使うアプリの場合、少なくとも当面はObjective-Cで良いのかな、という印象。
何にしろまだBetaということで、アップデートを楽しみにしつつマイペースに触っていこうかな、というところです。