trying to create my own image filter code?

122 views Asked by At

Just to make my basics of image processing clear i am trying to make a code to make an image filter which takes a kernel and convolve it to the whole image.

In short i am trying to replicate filter2d function of opencv, however it is giving me some unexpected result.

my code :

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

using namespace cv;
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Point anchor = Point(-1,-1);
    Mat kernel = (Mat_<float>(3,3))<<(1,1,1,1,-8,1,1,1,1);//for gaussianblur
    /*Mat kernel_inverse(kernel.size(),kernel.type());
    for(int i=0;i<kernel_inverse.rows;i++)
        for(int j=0;j<kernel_inverse.cols;j++)
        {
            kernel_inverse.at<uchar>(i,j)=kernel.at<uchar>(kernel.rows-i-1,kernel.cols-j-1);
        }*/
    Mat src  = imread("/home/vasu/SENSOVISION/Filter Testing/Elon Musk 8.jpg",0);
    imshow("source",src);
    Mat result(src.size(),src.type());
    //Mat result_inverse(src.size(),src.type());
    for(int i=1;i< src.rows;i++)
        for(int j=1;j<src.cols;j++)
        {
            result.at<uchar>(i,j)=((src.at<uchar>(i-1,j-1)*kernel.at<uchar>(0,0))+(src.at<uchar>(i-1,j)*kernel.at<uchar>(0,1))+(src.at<uchar>(i-1,j+1)*kernel.at<uchar>(0,2))+(src.at<uchar>(i,j-1)*kernel.at<uchar>(1,0))+(src.at<uchar>(i,j)*kernel.at<uchar>(1,1))+(src.at<uchar>(i,j+1)*kernel.at<uchar>(1,2))+(src.at<uchar>(i+1,j-1)*kernel.at<uchar>(2,0))+(src.at<uchar>(i+1,j)*kernel.at<uchar>(2,1))+(src.at<uchar>(i+1,j+1)*kernel.at<uchar>(2,2)));
            //result_inverse.at<uchar>(i,j)=((src.at<uchar>(i-1,j-1)*kernel_inverse.at<uchar>(0,0))+(src.at<uchar>(i-1,j)*kernel_inverse.at<uchar>(0,1))+(src.at<uchar>(i-1,j+1)*kernel_inverse.at<uchar>(0,2))+(src.at<uchar>(i,j-1)*kernel_inverse.at<uchar>(1,0))+(src.at<uchar>(i,j)*kernel_inverse.at<uchar>(1,1))+(src.at<uchar>(i,j+1)*kernel_inverse.at<uchar>(1,2))+(src.at<uchar>(i+1,j-1)*kernel_inverse.at<uchar>(2,0))+(src.at<uchar>(i+1,j)*kernel_inverse.at<uchar>(2,1))+(src.at<uchar>(i+1,j+1)*kernel_inverse.at<uchar>(2,2)));
        }
    imshow("result",result);
    //imshow("result_inverse",result_inverse);
    return a.exec();
}

by this code i am getting this

can someone tell me what am i doing wrong?

1

There are 1 answers

3
Andrey  Smorodov On BEST ANSWER

You do computations in unsigned char format, it will produce incorrect results. Make your computation in float, then put result to your result image.