opencv图像卷积操作

 

 opencv图像卷积操作

 

 代码:

#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
using namespace std;

int main()
{
    Mat src, dst, dst1;
    double t;
    //原图
    src = imread(".//pic//test.jpg",IMREAD_UNCHANGED);
    if (src.empty() || src.empty() || src.empty())
    {
        cout << "找不到图像" << endl;
        return -1;
    }
    
    namedWindow("opencv startup", CV_WINDOW_AUTOSIZE);
    imshow("input image", src);
    //矩阵的掩膜操作(手动)
    Mat resultImage;
    src.copyTo(resultImage);
    int nchannels = src.channels();
    int height = src.rows;
    int cols = src.cols;
    int width = src.cols * nchannels;
    const uchar* previous;
    const uchar* current;
    const uchar* next;
    uchar* output;
    t = (double)getTickCount();


    for (int row = 1; row < height - 1; row++)
    {
        previous = src.ptr<uchar>(row - 1);
        current = src.ptr<uchar>(row);
        next = src.ptr<uchar>(row + 1);
        output = resultImage.ptr<uchar>(row);
        for (int col = nchannels; col < nchannels * (src.cols - 1); col++)
        {
            *output = saturate_cast<uchar>(5 * current[col] - previous[col] - next[col] - current[col - nchannels] - current[col + nchannels]);
            output++;
        }
    }
    t = ((double)getTickCount() - t) / getTickFrequency();
    imshow("手动", resultImage);
    cout << "手动计算时间消耗了:" << t << endl;

    //矩阵的掩膜操作(调用api)
    Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
    //Mat kernel = (Mat_<float>(3, 3) << 1, 1, 1, 1, 1,1, 1, 1, 1);
    t = (double)getTickCount();
    filter2D(src, dst1, src.depth(), kernel);
    t = ((double)getTickCount() - t) / getTickFrequency();
    cout << "filter2D时间消耗了:" << t << endl;
    imshow("filter2D", dst1);
    waitKey(0);
    return 0;
}