Thursday, 25 February 2016

OpenCV C++ Code on Low Pass Median FIlter

This Opencv C++ Tutorial is about how to apply Low Pass Median Filter in OpenCV.
In the last tutorial we studied about what is a Low pass Filter ,along with one of its type i.e. Low Pass Averaging Filter.
This article describes the steps to apply Low Pass Median Filter to an Image.
 Low Pass Averaging Filter not only removes the noise but it also blurs the edges.(by blurring the image repeatedly till the noise can no longer be seen in the image)
Thus when ever the image is affected with Salt and Pepper noise it is preferable to work with Median Filtering.
The Steps to perform Median Filtering are:
1. Place the Mask Over the Image. (E.g 3*3)
2. Arrange the Pixel's value in the mask in the Increasing Order.
3. Choose the median value and place it at the centre.
4. Similarly move the mask over the image and repeat the same procedure (1-3) for the entire image.
Here is the OpenCv C++ Code for implementing Low Pass Median Filter :

//OpenCV C++ Code For Median FIltering
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "iostream"
 
using namespace cv;
using namespace std;
 
int main( )
{
    Mat src1,src2;
 int a;

 //Note: Array size should be greater than the square of Size of Mask
 int b[100];
 Scalar intensity1=0;

 //Read the Image
    src1 = imread("C:\\Users\\arjun\\Desktop\\opencv-logo.png", CV_LOAD_IMAGE_GRAYSCALE);
 src2 = src1.clone();

 //If image not found 
 if (!src1.data)                                                                          
     {  
      cout << "No image data \n";  
      return -1;  
     } 

  cout<<"Enter the mask Size =";
  cin>>a;

 //for loop for counting the number of rows and columns and displaying the pixel value at each point
   for (int i = 0; i < src1.rows-a; i++) 
   { 
    for (int j = 0; j < src1.cols-a; j++) 
     { 

   Scalar intensity2;
   int x=-1;
   for (int p = 0; p<a; p++) 
       { 
    
       for (int q = 0; q<a; q++) 
        { 

      intensity1 = src1.at<uchar>(i+p,j+q); 
      b[++x] =intensity1.val[0];
    }
  
 }
   int temp;
    for (int z=0;z<a*a;z++){
   for (int y=0;y<a*a;y++){
   if(b[y]>b[y++]){
    temp=b[y++];
      b[y++]=b[y];
      b[y]=temp;
   }
  }
    }
    src2.at<uchar>(i+(a-1)/2,j+(a-1)/2)=b[((a*a)-1)/2];
     } 
   }

  //Display the original image
   namedWindow("Display Image");                
   imshow("Display Image", src1); 

  //Display the Low Pass Filtered Image image
 namedWindow("Low Pass Filtered Image");     
 imshow("Low Pass Filtered Image", src2);  
 waitKey(0);
 return 0;
}

Input Image:
OpenCV C++ Code on Low Pass Median FIlter

Output Image:
OpenCV C++ Code on Low Pass Median FIlter Output

Note:Here we have choosen mask size=5.

No comments:

Post a Comment