证件相片一键换底过程

1、获取图片;

2、数据拼装;

3、Kmeans处理;

4、遮罩;

5、腐蚀、高斯模糊处理;

6、布景通道色替换;

TermCriteria 类
定义迭代算法终止条件的类。

构造函数
  参数:
  // type: 终止条件的类型,TermCriteria::Type之一。 
  // maxCount:要核算的最大迭代次数或元素。
  // epsilon:迭代算法停止的期望精度或参数更改。
  TermCriteria::TermCriteria(int _type, int _maxCount, double _epsilon)
    : type(_type), maxCount(_maxCount), epsilon(_epsilon) {}

KMeans 算法

KMeans算法能够完成简略的证件相片的布景切割提取与替换。

kmeans算法又名k均值算法。其算法思想大致为:先从样本会集随机选取 k 个样本作为簇中心,并核算所有样本与这 k 个“簇中心”的间隔,关于每一个样本,将其划分到与其间隔最近的“簇中心”地点的簇中,关于新的簇核算各个簇的新的“簇中心”。

- (UIImage *)changeBG{
    Mat img, img1, img2, img3;
    UIImageToMat(self.imgView.image, img);
    cvtColor(img, img1,COLOR_BGRA2BGR,3);//图片类型转换,将ARGB转RGB
    img2=img1.clone();
    Mat points = handleImgData(img1);
    //Kmeans处理
        int numCluster = 4;
        Mat labels;
        Mat centers;
        TermCriteria termCriteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 0.1);
        kmeans(points, numCluster, labels, termCriteria, 3, KMEANS_PP_CENTERS, centers);
        //遮罩
        Mat mask = Mat::zeros(img1.size(), CV_8UC1);
        int index = img1.rows * 2 + 2;
        int cindex = labels.at<int>(index, 0);//布景设置为0
        int height = img1.rows;
        int width = img1.cols;
        for (int row = 0; row < height; row++){
            for (int col = 0; col < width; col++){
                index = row * width + col;
                int label = labels.at<int>(index, 0);
                if (label == cindex){
                    img2.at<Vec3b>(row, col)[0] = 0;
                    img2.at<Vec3b>(row, col)[1] = 0;
                    img2.at<Vec3b>(row, col)[2] = 0;
                    mask.at<uchar>(row, col) = 0;
                }
                else{
                    mask.at<uchar>(row, col) = 255;
                }
            }
        }
        //腐蚀
    Mat k = getStructuringElement(MORPH_RECT, cv::Size(3, 3), cv::Point(-1, -1));
        erode(mask, mask, k);
        //高斯模糊
    GaussianBlur(mask, mask, cv::Size(3, 3), 0, 0);
        //布景色彩调整
        Vec3b color;//RGB三原色能够任意组合 ,留意下面的数组顺序是BGR
        color[0] = 255;  //B
        color[1] = 0;  //G
        color[2] = 0;  //R
        Mat result(img1.size(), img1.type());
        double d1 = 0.0;
        int r = 0, g = 0, b = 0;
        int r1 = 0, g1 = 0, b1 = 0;
        int r2 = 0, g2 = 0, b2 = 0;
        for (int row = 0; row < height; row++){
            for (int col = 0; col < width; col++){
                int m = mask.at<uchar>(row, col);
                if (m == 255){
                       result.at<Vec3b>(row, col) = img1.at<Vec3b>(row, col);//远景
                   }
                   else if (m == 0){
                       result.at<Vec3b>(row, col) = color;//布景
                   }else{
                       d1 = m / 255.0;
                       b1 = img1.at<Vec3b>(row, col)[0];
                       g1 = img1.at<Vec3b>(row, col)[1];
                       r1 = img1.at<Vec3b>(row, col)[2];
                       b2 = color[0];
                       g2 = color[1];
                       r2 = color[2];
                       b = b1 * d1 + b2 * (1.0 - d1);
                       g = g1 * d1 + g2 * (1.0 - d1);
                       r = r1 * d1 + r2 * (1.0 - d1);
                       result.at<Vec3b>(row, col)[0] = b;
                       result.at<Vec3b>(row, col)[1] = g;
                       result.at<Vec3b>(row, col)[2] = r;
                   }
               }
           }
    return MatToUIImage(result);
}
//拼装样本数据
Mat handleImgData(Mat& img){
    int width = img.cols;
    int height = img.rows;
    int count1 = width * height;
    int channels1 = img.channels();
    Mat points(count1, channels1, CV_32F, Scalar(10));
    int index = 0;
    for (int row = 0; row < height; row++){
        for (int col = 0; col < width; col++){
            index = row * width + col;
            Vec3b bgr = img.at<Vec3b>(row, col);
            points.at<float>(index, 0) = static_cast<int>(bgr[0]);
            points.at<float>(index, 1) = static_cast<int>(bgr[1]);
            points.at<float>(index, 2) = static_cast<int>(bgr[2]);
        }
    }
    return points;
}

马赛克处理

马赛克原理: 是把图画上某个像素点必定范围邻域内的所有点用邻域内左上像素点的色彩代替,这样能够模糊细节,但是能够保存大体的轮廓。就是用左上角的那个值,来替换右下方一个小方块的值,逐步进行替换即可。

//添加马赛克,level 值越大,马赛克块越大,越看越清
- (UIImage *)mosaic:(UIImage *)inputImage level:(int)level{
    //iOS图片转opencv的 Mat格式
    Mat srcImage;
   UIImageToMat(inputImage, srcImage);
    int width=srcImage.cols;//宽
    int height=srcImage.rows;//高
    Mat desImage;
    cvtColor(srcImage, desImage,COLOR_BGRA2BGR,3);//图片类型转换,将ARGB转RGB
    Mat cloneImage=desImage.clone();//克隆方针图
    //level为马赛克水平,值越大,马赛克块越大,越看不清楚,马赛克巨细是level个像素宽度,为了防止宽高溢出,遍历像素点时宽高都需求减去level
    int x=width-level;
    int y=height-level;
    for (int i=0; i<y; i+=level) {//i<总高,每次加level
        for (int j=0; j<x; j+=level) {//j小总宽,每次加level
            //创立马赛克矩形区域
            Rect2i mosaicRect=Rect2i(j,i,level,level);
            //填充数据
            Mat roi=desImage(mosaicRect);
            //确保矩形区域色彩一致,方框内色彩值都为i,j点位的值
            Scalar scaler = Scalar(
                cloneImage.at<Vec3b>(i,j)[0],
                cloneImage.at<Vec3b>(i,j)[1],
                cloneImage.at<Vec3b>(i,j)[2]
            );
            //将处理好的矩形区域拷贝到方针图上去
            Mat roiCopy = Mat(mosaicRect.size(),CV_8UC3,scaler);
            roiCopy.copyTo(roi);
        }
    }
    //转换opencv图为iOS图片格式
    UIImage *imag=MatToUIImage(desImage);
    return imag;
}

图画叠加

C++: void Mat::``copyTo(OutputArray m) const

C++: void Mat::``copyTo(OutputArray m, InputArray mask) const

这个函数能够复制图画到另一个图画或矩阵上,可选参数是掩码

由于叠加的图画巨细不必定相等,比方咱们这儿把一张小相片加到一张大相片上

咱们能够在大相片上设置一个和小相片一样大的感兴趣区域

不使用掩码的时分,咱们载入一张png,和一张jpg

//图画叠加,添加水印,未使用掩码
- (UIImage *)roi:(UIImage *)inputImage{
    Mat srcImg,logoImg;
    UIImageToMat(inputImage, srcImg);
    UIImage *logo=[UIImage imageNamed:@"8.jpg"];
    UIImageToMat(logo, logoImg);
    Mat imgROI=srcImg(cv::Rect(0,0,logoImg.cols,logoImg.rows));
    logoImg.copyTo(imgROI);
    return MatToUIImage(srcImg);
}