OpenCV-iOS计算图片相似度

更新停留在17年?????

demo下载

  • 需求分析:

1、寻宝活动,商家藏宝并将场景拍照上传至服务器,用户根据线索到达指定地点,打开app进行实时扫描,如扫描到的图片与服务器的图片匹配成功,则视为中奖;

2、OpenCV中用于图片对比及识别的算法较多,具体原理及优缺点本文不做介绍,demo中用到的是特征点对比中的ORB算法;

3、本次需求中用到两个算法:特征点-ORB和直方图;
经反复测试发现特征点对比较为适合棱角分明的场景,比如桌子/电脑等;而直方图对比较为适合复杂且棱角较少的场景,比如办公室的盆栽类;(ps:测试分为室内测试及室外测试,且测试次数及测试量都不太大,结论仅限于参考)

  • OpenCV集成

1、OpenCV下载:官网地址

2、demo中OpenCV版本为3.4.3;

3、添加依赖库:


OpenCV依赖库
  • 功能开发:

1、拍照上传:

1)将.m文件后缀改为.mm;

2)导入头文件(务必放在所有头文件之上)

#import 
#import 
#import 
#import 

3)打开相机具体实现:

@interface CaptureView()

@property (strong, nonatomic)  UIImageView *CvImageV;

@property (nonatomic,retain) CvVideoCamera *videoCamera;

@end

@implementation CaptureView

- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
    if (self) {
    
        [self setupCvVideoCamera];
    
    }
     return self;
}

// MARK: - init
-(void)setupCvVideoCamera{

    self.CvImageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];

    self.videoCamera = [[CvVideoCamera  alloc]initWithParentView:self.CvImageV];

    self.videoCamera.delegate = self;
    self.videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionBack;

    self.videoCamera.defaultAVCaptureSessionPreset = AVCaptureSessionPresetiFrame960x540;
    self.videoCamera.defaultAVCaptureVideoOrientation = AVCaptureVideoOrientationPortrait;

    self.videoCamera.grayscaleMode = NO;
    self.videoCamera.defaultFPS = 30;
    [self addSubview:self.CvImageV];
}

// MARK: - CvVideoCameraDelegate
- (void)processImage:(cv::Mat &)image{

    // 将Mat转换为Xcode的UIImageView显示
    UIImage *currentImage = MatToUIImage(image);
}

// MARK: - event and response
// 开启
- (void)start{
    [self.videoCamera start];
}

// 暂停
- (void)stop{
    [self.videoCamera stop];
}

4)问题:opencv返回的图片矩阵为BGR,需要转成RGB来上传,具体代码见demo

2、图片对比:

1)将.m文件后缀改为.mm;

2)导入头文件(务必放在所有头文件之上)

#import 
#import 
#include "opencv2/core/core.hpp"
#include 
#include 

3)实现代码:

 /**
 @param boxImage 模板图片
 @param senceImage 实时图片
 @return 对比结果(见图)
 */
 -(UIImage *)similarlyMatchWithBox:(UIImage *)boxImage andSence:(UIImage *)senceImage{

    if (boxImage && senceImage) {
    
        cv::Mat sence,box;
        box = [self cvMatFromUIImage:boxImage];
        sence = [self cvMatFromUIImage:senceImage];
    
        cvtColor(box, box, CV_RGBA2RGB);
        cvtColor(sence, sence, CV_RGBA2RGB);
    
        vector keyPoints_obj, keyPoints_sence;
        Ptr detector = ORB::create();
    
        detector->detect(box, keyPoints_obj);
        detector->detect(sence, keyPoints_sence);
    
        Mat description_box,description_sence;
    
        detector->compute(box, keyPoints_obj, description_box);
        detector->compute(sence, keyPoints_sence, description_sence);
        vector matches;
    
        Ptr matcher = DescriptorMatcher ::create(cv::BFMatcher::BRUTEFORCE);
    
        // 处理拍的区域为黑色,比如手机平放在桌面上,会闪退
        if (description_sence.cols <= 0) {
            return nil;
        }
    
        if (description_sence.rows <= 0) {
            return nil;
        }
    
        matcher->match(description_box, description_sence, matches);
    
        // 发现匹配
        vector good_matches;
    
        for (unsigned int i = 0; i < matches.size(); i++) {
            //distance 值根据实际开发来调试
            if (matches[i].distance <= 320) {
                good_matches.push_back(matches[i]);
            }
        }
    
        Mat imgMatches;
        drawMatches(box,keyPoints_obj,sence,keyPoints_sence,good_matches,imgMatches,Scalar::all(-1),Scalar::all(-1),vector(),DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
    
        UIImage *m = [self UIImageFromCVMat:imgMatches];
        return m;
    }

    return nil;
}

4)具体代码见demo中ImageCompared文件;

5)问题:

① 相机拍到黑色时会崩溃:可通过description_sence.cols <= 0 && description_sence.rows <= 0来判断;这个坑我和安卓都爬了好久才爬出来;(悄悄告诉你我先爬出来的,美滋滋)

② 存储在服务器的模板图可多上传几张,一张图片匹配成功率会很低:可设置至少上传X张,且在上传的时候也进行匹配,匹配率达到某个值则可上传,否则要求商家重拍,防止上传的图片不是同一个场景;

③ 内存问题:实时扫描且进行相似度对比消耗内存非常大,很快就会内存溢出导致闪退,我的解决方法是设置为每隔X秒进行一次匹配,时间可自己调试然后给定;

6)匹配结果图:


匹配结果
  • 最后:OpenCV里的学问太多了,这次需求甲方爸爸赶得急是一方面,之前没了解过也是真的,熬了几个通宵才搞定,大概算是一只脚迈进去了,如果二期需求有时间排的话可能另一只脚也就能迈进去了,如果没有的话就此打住。

你可能感兴趣的:(OpenCV-iOS计算图片相似度)