如何在C ++中实现拉普拉斯过滤器

时间:2019-04-19 14:50:40

标签: c++ opencv image-processing

我实现了自己的Laplace过滤器,但是它看起来不像Gimp中的Laplace过滤器。怎么了?

我的尝试 enter image description here

G子 enter image description here

cv::Mat ImageManipulation::mylaplace_filter(cv::Mat image){
    int laplace_mask[9] = {0, -1, 0, -1, 4, -1, 0, -1, 0};
    int tmp = 0;
    int counter = 0;
    cv::Mat laplaceImage = cv::Mat::ones(image.rows-2,image.cols-2,CV_8U);
    for(int i = 1; i<image.rows-1; i++){
        for(int j = 1; j<image.cols-1; j++){

            for(int k = i-1; k<i+2; k++){
                for(int l = j-1; l<j+2; l++){
                    tmp += laplace_mask[counter] * static_cast<int>(image.at<uchar>(k,l));
                    counter++;
                }
            }
            std::cout << tmp/9 << std::endl;
            laplaceImage.at<uchar>(i-1,j-1) = tmp/9;
            tmp = 0;
            counter = 0;
        }
    }
    return laplaceImage;
}

2 个答案:

答案 0 :(得分:1)

进入循环之前,您必须更改图像类型“ laplaceImage”,正如@Cris Luengo所评论的那样,无需除以9:

cv::Mat ImageManipulation::mylaplace_filter(cv::Mat image)
{
    int laplace_mask[9] = { 0, -1, 0, -1, 4, -1, 0, -1, 0 };
    int tmp = 0;
    int counter = 0;
    cv::Mat laplaceImage = cv::Mat::ones(image.rows - 2, image.cols - 2, CV_32F);

    for (int i = 1; i < image.rows - 1; i++)
    {
        for (int j = 1; j < image.cols - 1; j++)
        {

            for (int k = i - 1; k < i + 2; k++)
            {
                for (int l = j - 1; l < j + 2; l++)
                {
                    tmp += laplace_mask[counter] * static_cast<int>(image.at<uchar>(k, l));
                    counter++;
                }
            }
            std::cout << tmp << std::endl;
            laplaceImage.at<float>(i - 1, j - 1) = tmp;
            tmp = 0;
            counter = 0;
        }
    }
    return laplaceImage;
}

之后,如果要显示“ laplaceImage”或将其保存在硬盘上,可以在0到255之间进行调整,然后将其转换为CV_8U。

答案 1 :(得分:0)

这是非常简单的代码,这将有助于了解基础知识

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>

using namespace cv;


int main(int argc, char** argv){

    Mat src_gray, dst;

    Mat src = imread("ball.jpg");
    int kernel = 3;
    Mat filter = (Mat_ <double>(3,3) << 1,1,1,1,-8,1,1,1,1); // Laplace Filter

    filter2D(src, dst, -1, filter);
    imshow("Simple Function", dst);
    imshow("Simple Source", src);

    waitKey(0);

    return 0;
}

制作自己的线性滤波器! https://docs.opencv.org/3.4/d4/dbd/tutorial_filter_2d.html

拉普拉斯算子 https://docs.opencv.org/3.4/d5/db5/tutorial_laplace_operator.html