opencv矩阵的掩模操作


main.cpp

#include 
#include 

using namespace cv;

int main(int argc, char **argv) {
    Mat image;
    //    加载图片
    image = imread("../../picture/bg1.webp", 1);
    if (!image.data) {
        printf("No image data \n");
        return -1;
    }
    //    创建窗口
    namedWindow("Source Image", WINDOW_AUTOSIZE);
    //    展示图片
    imshow("Source Image", image);
    Mat dst = Mat::zeros(image.size(), image.type());
    //    掩膜实现
    //    int cols = (image.cols - 1) * image.channels();
    //    int offset = image.channels();
    //    int rows = image.rows;
    //    for (int row = 1; row < (rows - 1); row++) {
    //        const uchar *previous = image.ptr(row - 1);
    //        const uchar *current = image.ptr(row);
    //        const uchar *next = image.ptr(row + 1);
    //        uchar *output = dst.ptr(row);
    //        for (int col = offset; col < cols; ++col) {
    //            // 掩模计算:I(i,j) = 5*I(i,j) - [I(i,j-1) + I(i,j+1) + I(i-1,j) + I(i+1,j)]
    //            output[col] = saturate_cast(
    //                    5 * current[col] - (current[col - offset] + current[col + offset] + previous[col] + next[col]));
    //        }
    //    }
    //    opencv掩模实现
    Mat kernel = (Mat_(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
    filter2D(image, dst, image.depth(), kernel);
    namedWindow("contrast image", WINDOW_AUTOSIZE);
    imshow("contrast image", dst);
    //    等待按键
    waitKey(0);
    return 0;
}