引用自:
http://www.jianshu.com/p/b398da410451
因为OpenCV是用C++编写的,所以只能用.mm来使用,然后再用bridging-header.h来转到swift里来使用。
OpenCVUtil.h
#import <Foundation/Foundation.h>
@class UIImage;
@interface OpenCVUtil : NSObject
+(UIImage *) convertImage:(UIImage *)image;
@end
OpenCVUtil.mm
//下面的#ifdef只能放在上面,如果放在#import "OpenCVUtil.h"下面就出错。
#ifdef __cplusplus
#import <opencv2/opencv.hpp>
#import <opencv2/imgproc/types_c.h>
#import <opencv2/imgcodecs/ios.h>
#endif
#import "OpenCVUtil.h"
using namespace cv;
@implementation OpenCVUtil
+(UIImage *) convertImage:(UIImage *)image{
Mat cvImage;
UIImageToMat(image, cvImage);
if (!cvImage.empty()) {
Mat gray;
//将图像转成灰度显示
cvtColor(cvImage, gray, CV_RGB2GRAY);
//应用高斯滤波器出除小的边缘
GaussianBlur(gray, gray, cv::Size(5,5), 1.2,1.2);
//计算与画布轮廓
Mat edges;
Canny(gray, edges, 0, 50);
//使用白色填充
cvImage.setTo(Scalar::all(100));
//修改轮廓颜色 scalar 四个属性分别是R G B Alpha
cvImage.setTo(Scalar(255,0,225,255),edges);
//将Mat转换成UIImageView
return MatToUIImage(cvImage);
//用gray来转出UIImage,只能得到灰度图,不像上面的可以用彩色。
// gray.setTo(Scalar::all(225));
// gray.setTo(Scalar(0,255,0,255),edges);
// return MatToUIImage(gray);
}
return nil;
}
@end
HumanFaceRecognition-Bridging-Header.h
#import "OpenCVUtil.h"
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let image = OpenCVUtil.convert(#imageLiteral(resourceName: "circle"))
let iv = UIImageView(image: image)
iv.frame.origin = CGPoint(x: 20, y: 20)
iv.frame.size = CGSize(width: 200, height: 200)
view.addSubview(iv)
}
}