Xcode+OpenCV3.4.0 折腾(3)

~ 开始使用OpenCV了 ~

今天尝试的是 矩阵的掩膜操作

内容来自于
https://www.bilibili.com/video/av17748771/index_3.html#page=3

设定一个掩膜算子(是这么叫吗。。)

 0 -1  0
-1  5 -1
 0 -1  0

用于提高某张图片的对比度

算法为

I(i,j) = 5 * I(i,j) - (I(i-1,j) + I(i+1,j) + I(i,j-1) + I(i,j+1))


先用一个最粗暴的办法实现一下

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

using namespace cv;

int main(int argc, const char * argv[])
{
    Mat src = imread("/Users/Aphas1a/Documents/C/OpenCV/opencvtest/test1.png");
    if(src.empty())
    {
        printf("could not load image...
") ;
        return 1;
    }
    namedWindow("test1",CV_WINDOW_AUTOSIZE);
    imshow("test1", src); // 输出原始图像
    
    // 粗暴方法开始
    Mat dst = Mat::zeros(src.rows, src.cols, src.type());
    int cols = (src.cols - 1) * src.channels(); // *3是因为彩色图通道数为3
    int rows = src.rows - 1;
    int offsetx = src.channels();
    for(int row = 1; row < rows - 1; row++)
    {
        const uchar* previous = src.ptr<uchar>(row - 1);
        const uchar* current = src.ptr<uchar>(row);
        const uchar* next = src.ptr<uchar>(row + 1);
        uchar* output = dst.ptr<uchar>(row);
        for (int col = offsetx; col < cols ; col++)
        {
            output[col] = saturate_cast<uchar>(5 * current[col] - (current[col - offsetx] + current[col + offsetx] + previous[col] + next[col]));
        }
    }
    // 粗暴方法结束 

    namedWindow("after",CV_WINDOW_AUTOSIZE);
    imshow("after", dst);  // 输出对比图像

    waitKey(0);
    return 0;
}

然而OpenCV肯定不会这么不好用,针对上面的问题,它有个函数是filter2D()

尝试使用一下这个函数,用下面的代码替换掉上面代码的粗暴方法段

Mat kernal = (Mat_<char>(3,3) << 0,-1,0,-1,5,-1,0,-1,0);
Mat dst;
filter2D(src, dst, src.depth(), kernal);

效果一样,而且简单了很多

看一下两种方法使用所花时间好了,使用getTickCount()和getTickFrequency()函数

可以看到这两种方法分别用了多久

double start_time = getTickCount();

/* 这里是用来被计时的代码段 */

double use_time = (getTickCount() - start_time) / getTickFrequency();
printf("use time: %f s
", use_time);

个人测试

粗暴方法:0.01889 s    |    自带函数:0.00969 s

~ 这次就这些啦 ~

原文地址:https://www.cnblogs.com/aphas1a/p/8353177.html