Saturday, April 18, 2015

Image Filtering with OpenCV

Last year I wanted put my hands on JavaCV and play little bit with that. But with time I couldn't continue that. Few weeks back I again got that crazy feel "The Machine" :D So I wanna start it again. But this time with c++.

Install OpenCV
I found a nice post that describe step by step to install OpenCV on ubuntu. You can follow that tutorial and get OpenCV on your machine. (If you are on Windows then it is just installing the .exe)
Installing OpenCV 3.0.0 on Ubuntu 14.04
In the post he is using OpenCV 3.0 alpha version. But now beta version is also available. I'm using the Beta version here. Just download the beta release from the officail OpenCV website. http://opencv.org/downloads.html
Then you can follow the same steps as mentioned.

Image Filtering
I'm not going to describe about what is image filtering or why we need that. You can find plenty of information about these topics if you really keen on. I'm just gonna show up the code that can be use to do Mode filtering and Median filtering.

Median Filtering
In Mode filtering what we do is simply break image into 3x3 segments and assign the median of those pixel values of each segment to the center pixel of the each segment.
Mat image = imread("poi.jpg", CV_LOAD_IMAGE_GRAYSCALE); // change the image name and path as u want
Mat MedianFilteredImage(image.rows, image.cols, CV_8UC1);
for(int x= 1; x < image.cols-1; x++){
for(int y =1 ; y<image.rows-1;y++){
float median = 0.0;
int value[9];
int i = 0;
for(int k = -1; k <= 1;k++){
for( int j = -1; j <=1; j++){
value[i++] = image.at<uchar>(y+k , x+j);
}
}
sort(value, value+9);
median = value[4];
MedianFilteredImage.at<uchar>(y,x) =(uchar) median;
}
}
cv::imshow("Grayscaled Image", image); // Showing the original image(gray scaled image)
cv::imshow("Median filtered Image", MedianFilteredImage); // Median filtered image
view raw gistfile1.cpp hosted with ❤ by GitHub

Mode Filtering
In Mode filtering what we do is simply break image into 3x3 segments and assign the mode value of each segment to the center pixel of the each segment.
Mat image = imread("poi.jpg", CV_LOAD_IMAGE_GRAYSCALE);
Mat ModeFilteredImage(image.rows, image.cols, CV_8UC1);
for(int x= 1; x < image.cols-1; x++){
for(int y =1 ; y<image.rows-1;y++){
int value[9];
int i = 0;
for(int k = -1; k <= 1;k++){
for( int j = -1; j <=1; j++){
value[i++] = image.at<uchar>(y+k , x+j);
}
}
sort(value, value+9); //sort the array
// find the mode. You can move this to a separate method
int number = value[0];
int mode = number;
int count = 1;
int countMode = 1;
for (int i=1; i<9; i++)
{
if (value[i] == number)
{
count++;
}
else
{
if (count > countMode)
{
countMode = count;
mode = number;
}
count = 1;
number = value[i];
}
}
ModeFilteredImage.at<uchar>(y,x) =(uchar) mode;
}
}
cv::imshow("Grayscaled Image", image);
cv::imshow("Mode filtered Image", ModeFilteredImage);
view raw gistfile1.cpp hosted with ❤ by GitHub

No comments:

Post a Comment