简体   繁体   中英

Am I doing the mean filter correct? What do i need to change to make it work?

The problem is i dont know how to get the math done properly when using a mean filter. 3x3 kernel with a weight value of 1 in all 9 kernels. I got some help to use the sum part, but i do not know if it works correctly, i certainly cant build.

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

using namespace cv;
using namespace std;

int main()

{
    Mat gray_image, convolued_image;

    gray_image = imread( "C:/1.jpg", CV_LOAD_IMAGE_GRAYSCALE);   // Read the file
    convolued_image = gray_image;


    if(!gray_image.data )                                     // Check for invalid input

    {
        cout <<  "Could not open or find the image" << std::endl ;
        return -1;
    }

    namedWindow( "RGB Input", CV_WINDOW_AUTOSIZE );    
    imshow( "RGB Input", gray_image );                 



     Mat meanImg;
       gray_image.copyTo(meanImg);

      namedWindow( "meanImg", CV_WINDOW_AUTOSIZE );    
    imshow( "meanImg", meanImg );  


        waitKey(0);    

        for (int y = 0; y < gray_image.rows; y++)
       {
               for (int x = 0; x < gray_image.cols; y++)
              {
                      int intesity = gray_image.at<uchar>(y,x);       
                      int sum = gray_image.at<uchar>(y+1,x+1);
                            sum = gray_image.at<uchar>(y+1,x);
                            sum = gray_image.at<uchar>(y+1,x-1);
                            sum = gray_image.at<uchar>(y,x-1);
                            sum = gray_image.at<uchar>(y,x+1);
                            sum = gray_image.at<uchar>(y-1,x-1);
                            sum = gray_image.at<uchar>(y+1,x);
                            sum = gray_image.at<uchar>(y+1,x+1);

                    int mean = sum/9;

                meanImg.at<uchar>(y,x) = mean;


              }
       }


    return 0;
}
sum = gray_image.at<uchar>(y+1,x);
sum = gray_image.at<uchar>(y+1,x-1);
sum = gray_image.at<uchar>(y,x-1);

Your variable is named sum , but you aren't actually adding anything here.

You also start off your loop by reading outside the bounds of the image.

Once you get it to build, you'll have these bugs to attend to:

You left out a character in

sum = gray_image.at<uchar>(y+1,x);

These lines replace the value of sum with a new value.

To actually add them together, do

sum += gray_image.at<uchar>(y+1,x);

You're also indexing outside the image bounds - you need to handle the cases where x or y are 0 or their respective maximum properly.

And in the inner loop, you say y++ where you should say x++ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM