Saturday, March 28, 2015

Digital Image processing with c++ ( Chapter 6 ) - Image Smoothing (Median filter)

Hi All Today i'm going explain you how to add median filter to image

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

using namespace cv;
using namespace std;


int main()
{
 Mat RGBImage;

 RGBImage =imread("c:/Pictures/noisy.jpg");

 Mat grayScaleImage(RGBImage.size(),CV_8UC1);
 grayScaleImage=Scalar(0);
 Mat FinalImage(RGBImage.size(),CV_8UC1);
 cvtColor(RGBImage,grayScaleImage,CV_RGB2GRAY);
 int kernalWidth=3;
 int kernalHeight=3;
 int kernalSize=kernalHeight*kernalWidth;
 int rows=grayScaleImage.rows;
 int cols=grayScaleImage.cols;
 int pixelArray[9];

 int verticleImageBound=(kernalHeight-1)/2;
 int horizontalImageBound=(kernalWidth-1)/2;

 for(int row=0+verticleImageBound;row<rows-verticleImageBound;row++){

  for(int col=0+horizontalImageBound;col<cols-horizontalImageBound;col++){


   int pixelArrayIndex=0;
   for(int kRow=0;kRow<kernalHeight;kRow++){
    for(int kCol=0;kCol<kernalWidth;kCol++){
     pixelArray[pixelArrayIndex]=grayScaleImage.at<uchar>(kRow+row-verticleImageBound,kCol+col-horizontalImageBound);
     pixelArrayIndex++;
    }
   }


   int elements = sizeof(pixelArray) / sizeof(pixelArray[0]); 
   sort(pixelArray, pixelArray + elements);
   FinalImage.at<uchar>(row, col)=pixelArray[(kernalSize+1)/2];

  }

 }


 namedWindow("Original Image",1);
 imshow("Original Image",grayScaleImage);

 namedWindow("Filtered Image",1);
 imshow("Filtered Image",FinalImage);

 waitKey();
 return 0;
}




When you run this code you see results like this



1 comment:

C Chan said...

Nice work machan, this is really helpful :)