opencv 创建图像mask

2020-12-09  本文已影响0人  此间不留白

创建图像mask

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

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

原始图像如下所示:


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


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

#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 }; //不相等

上一篇下一篇

猜你喜欢

热点阅读