掩模操作

#include<opencv2/opencv.hpp>
#include<iostream>

using namespace std;
using namespace cv;

int main(int argc, char **argv)
{
    Mat src = imread("D:/meinv.jpg");
    cvNamedWindow("src_image", CV_WINDOW_AUTOSIZE);
    imshow("src_image", src);
    
    //方法一:传统方法

    int channel = src.channels(); //获取图像的通道数
    cout << "通道的个数为:" << channel << endl;
    int row = src.rows;
    cout << "图像的行数为:" << row << endl;
    int col = src.cols;
    cout << "图像的列数为:" << col << endl;
    Mat outMat = Mat(src.size(), src.type());
    for (int i = 1; i < row - 1; i++) {
        for (int j = channel; j < (col - 1)*channel; j++) {
            outMat.ptr<uchar>(i)[j] = saturate_cast<uchar>(5 * src.ptr<uchar>(i)[j] -
                (src.ptr<uchar>(i - 1)[j] +
                src.ptr<uchar>(i + 1)[j] +
                src.ptr<uchar>(i)[j - channel] +
                src.ptr<uchar>(i)[j + channel]));
        }
    }
    cvNamedWindow("掩模之后的图像", CV_WINDOW_AUTOSIZE);
    imshow("掩模之后的图像", outMat);
   
    //方法二:调用API

    Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
    filter2D(src, outMat, src.depth(), kernel);
    imshow("filter2D变化之后的图像", outMat);
    waitKey(0);
    return 0;
}

显示结果:

(1)源图像

(2)掩模后的图像

原文地址:https://www.cnblogs.com/carlber/p/9609740.html