iOS通过OpenCV实现马赛克

iOS集成OpenCV的两个常见错误

问题一:enum { NO, GAIN, GAIN_BLOCKS }; Expected identifier

只要把NO修改成 NO_EXPOSURE_COMPENSATOR 或 NO_EXPOSURE_COMPENSATOR = 0

解决:把调用了OpenCV文件的.m文件修改为.mm,以及viewController.m修改为viewController.mm

问题二:core.hpp header must be compiled as C++ 或 base.hpp header must be compiled as C++

核心代码及讲解

+ (UIImage *)opencvImage:(UIImage *)image mosaciLevel:(int)level{
    //实现功能
    //1.iOS图片转成OpenCV图片(Mat矩阵)
    Mat mat_image_src;
    UIImageToMat(image, mat_image_src);
    //2.确定宽高
    int width = mat_image_src.cols;
    int height = mat_image_src.rows;
    //*这里有个坑,OpenCV里面支持RGB的处理。所以我们需要把ARGB转成RGB
    Mat mat_image_dst;
    
    cvtColor(mat_image_src, mat_image_dst,CV_RGBA2RGB, 3);
    //新的图片,不影响新的图片
    Mat mat_image_clone = mat_image_dst.clone();
    
    //3.mosaic处理
    int x = width - level;
    int y = height - level;
    
    for (int i = 0; i < y; i += level) {
        for (int j = 0; j < x; j += level) {
            //1.创建马赛克矩形区域
            Rect2i mosaicRect = Rect2i(j,i,level,level);
            //2.填充Rect2i区域->填充数据->原始数据
            Mat roi = mat_image_dst(mosaicRect);
            //3.让整个矩形的区域颜色值保持一致
            //mat_image_clone.at(i,j)->像素点(颜色值组成->多个)->ARGB->数组
            //mat_image_clone.at(i,j)[0]->R值
            //mat_image_clone.at(i,j)[1]->G值
            //mat_image_clone.at(i,j)[2]->B值
            Scalar scalar = Scalar(
                   mat_image_clone.at(i,j)[0],
                   mat_image_clone.at(i,j)[1],
                   mat_image_clone.at(i,j)[2]
                   );
            //将处理好矩形区域->数据->拷贝到图片上去->修改后的数据
            //CV_:表示框架命名空间
            //8表示:32位色->ARGB-> 8位-->4字节
            //U
            //两种类型:有符号类型:(Sign->有符号->简写“s”) 无符号类型(Unsign->正数->"U")
            //有符号类型:0-255
            //无符号类型:-128-127
            //C:char类型
            //3表示:3通道->RGB
            Mat roiCopy = Mat(mosaicRect.size(),CV_8UC3,scalar);
            roiCopy.copyTo(roi);
        }
    }
    
    //4.Opencv图片转换成iOS图片
    return MatToUIImage(mat_image_dst);
    
}

效果图


Simulator Screen Shot - iPhone 8 Plus - 2018-06-07 at 15.39.41.png

你可能感兴趣的:(iOS通过OpenCV实现马赛克)