美文网首页
opencv 创建图像mask

opencv 创建图像mask

作者: 此间不留白 | 来源:发表于2020-12-09 17:10 被阅读0次

    创建图像mask

    《learning opencv》第五章第6题解决方案

    创建一副图像mask的过程可以分为以下步骤:

    • 将原始图像通道分离,获取红绿蓝三通道的第二个绿色通道;
    • 克隆绿色通道矩阵两次,得到个矩阵clone1,clone2;
    • 寻找绿色通道矩阵的最小值\min和最大值\max
    • 将clone1 的所有元素值按照以下公式设定:
      thresh = (\max - \min )/2.0
    • 将clone2 的所有值设置为0,并用compare()函数处理clone2 图像,得到最终的效果图。

    原始图像如下所示:


    对原始图像进行通道分离,得到绿色通道的图像,如下所示:


    最后,实现代码如下所示:

    #include<opencv2/opencv.hpp>
    #include<iostream>
    #include<vector>
    using namespace cv;
    
    int main()
    {
        //加载一副图像,按照三通道分离
        Mat m = imread("daminggong.png");
        std::vector<cv::Mat> plane;
        split(m, plane);
        //找到绿色通道的矩阵
        Mat green = plane[1];
        imwrite("green.png", green);
        // 绿色通道被克隆两次
        Mat clone1 = green.clone();
        Mat clone2 = green.clone();
        // clone1 所有元素 (Max-Min)/2.0
        double minPixel, maxPixel;
        int minPixelIdx, maxPixelIdx;
        minMaxIdx(green, &minPixel, &maxPixel, &minPixelIdx, &maxPixelIdx);
        double thresh = (unsigned char)(maxPixel - minPixel) / 2.0;
        int ithresh = (int)thresh;
        // 最大值和最小值所求的的中值,设置为clone1的值
        clone1 = Mat(clone1.size(), clone1.type(), Scalar(ithresh));
        // clone2 的所有值设置为0
        clone2 = Mat(clone2.size(), clone2.type(), Scalar(0));
    
        compare(green, clone1, clone2, CMP_GE);
        subtract(green, thresh / 2, green, clone2);
    
        imshow("clone2", clone2);
        imwrite("mask.png", clone2);
        waitKey(0);
        return 0;
    }
    

    实现效果如下图所示:


    compare()函数实现逐像素比较两个单通道图像的功能,若满足cmpop条件,则dst被填充为255,否则填充为0

     void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop);
    
    cmpop 有以下几种情况:
    enum { CMP_EQ=0,    //相等
        CMP_GT=1,   //大于
        CMP_GE=2,   //大于等于
        CMP_LT=3,   //小于
        CMP_LE=4,   //小于等于
        CMP_NE=5 }; //不相等
    
    

    相关文章

      网友评论

          本文标题:opencv 创建图像mask

          本文链接:https://www.haomeiwen.com/subject/xfghgktx.html