欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【OpenCV】矩阵掩模操作

程序员文章站 2024-03-25 10:23:18
...

  矩阵掩模操作是指根据一个掩码矩阵(也称为内核kernel)重新计算图像中每个像素的值。掩码可以控制改变相邻像素和当前像素对新像素值的影响,从而产生新的图像像素。

  本节通过图像锐化来比较图像指针运算与掩模操作的运行结果,观察运行时间的差异。

【OpenCV】矩阵掩模操作


#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>

using namespace std;
using namespace cv;

void sharpen(const Mat& myImage, Mat& Result);

int main(int argc, char* grav[])
{
    char* filename = "../data/fruits.jpg";

    Mat src, dst0, dst1;
    src = imread(filename, IMREAD_COLOR);
    if (src.empty())
    {               
        // cerr(无缓冲标准错误):没有缓冲,发送给它的内容立即被输出
        cerr << "Can't open image" << endl;     
        return -1;
    }

    namedWindow("Input", WINDOW_AUTOSIZE);
    namedWindow("Output", WINDOW_AUTOSIZE);

    imshow("Input", src);                                       // 显示原图像

    double t = (double)getTickCount();                          // 计算hand-coded方法的时间
    sharpen(src, dst0);
    t = ((double)getTickCount() - t) / getTickFrequency();
    cout << "Hand written function time passed in seconds:" << t << endl;
    imshow("Output", dst0);

    Mat kernel = (Mat_<char>(3, 3) << 0,-1,0,-1,5,-1,0,-1,0);

    t = (double)getTickCount();                                 // 计算矩阵掩模方法的时间
    filter2D(src, dst1, src.depth(), kernel);                   // 滤波filter2D函数
    t = ((double)getTickCount() - t) / getTickFrequency();
    cout << "Built-in filter2D time passed in seconds:" << t << endl;
    imshow("Output", dst1);

    waitKey(0);
    return 0;   
}

void sharpen(const Mat& myImage, Mat& Result)
{
    CV_Assert(myImage.depth() == CV_8U);                        // 只允许uchar型图像

    const int nChannels = myImage.channels();
    Result.create(myImage.size(), myImage.type());

    for (int j = 1; j < myImage.rows - 1; ++j)                  // 遍历图像
    {
        const uchar* previous = myImage.ptr<uchar>(j - 1);
        const uchar* current = myImage.ptr<uchar>(j);
        const uchar* next = myImage.ptr<uchar>(j + 1);

        uchar* output = Result.ptr<uchar>(j);

        for (int i = nChannels; i < nChannels*(myImage.cols - 1); ++i)
        {
            // saturate_cast原理: if(data<0)  data = 0;   if (data>255)   data = 255 

            *output++ = saturate_cast<uchar>(5 * current[i]     // 防止数据溢出
                - current[i - nChannels] - current[i + nChannels] - previous[i] - next[i]);         
        }
    }

    Result.row(0).setTo(Scalar(0));                             // 图像四边未处理像素设为0
    Result.row(Result.rows - 1).setTo(Scalar(0));
    Result.col(0).setTo(Scalar(0));
    Result.col(Result.cols - 1).setTo(Scalar(0));
}

运行结果

Hand written function time passed in seconds:0.0174564
Built-in filter2D time passed in seconds:0.00683035

【OpenCV】矩阵掩模操作

【OpenCV】矩阵掩模操作

相关标签: opencv