This repository was archived by the owner on Oct 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathbilateral_filter.cpp
More file actions
72 lines (57 loc) · 2.05 KB
/
bilateral_filter.cpp
File metadata and controls
72 lines (57 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
float distance(int x, int y, int i, int j) {
return float(sqrt(pow(x - i, 2) + pow(y - j, 2)));
}
double gaussian(float x, double sigma) {
return exp(-(pow(x, 2))/(2 * pow(sigma, 2))) / (2 * CV_PI * pow(sigma, 2));
}
void applyBilateralFilter(Mat source, Mat filteredImage, int x, int y, int diameter, double sigmaI, double sigmaS) {
double iFiltered = 0;
double wP = 0;
int neighbor_x = 0;
int neighbor_y = 0;
int half = diameter / 2;
for(int i = 0; i < diameter; i++) {
for(int j = 0; j < diameter; j++) {
neighbor_x = x - (half - i);
neighbor_y = y - (half - j);
double gi = gaussian(source.at<uchar>(neighbor_x, neighbor_y) - source.at<uchar>(x, y), sigmaI);
double gs = gaussian(distance(x, y, neighbor_x, neighbor_y), sigmaS);
double w = gi * gs;
iFiltered = iFiltered + source.at<uchar>(neighbor_x, neighbor_y) * w;
wP = wP + w;
}
}
iFiltered = iFiltered / wP;
filteredImage.at<double>(x, y) = iFiltered;
}
Mat bilateralFilterOwn(Mat source, int diameter, double sigmaI, double sigmaS) {
Mat filteredImage = Mat::zeros(source.rows,source.cols,CV_64F);
int width = source.cols;
int height = source.rows;
for(int i = 2; i < height - 2; i++) {
for(int j = 2; j < width - 2; j++) {
applyBilateralFilter(source, filteredImage, i, j, diameter, sigmaI, sigmaS);
}
}
return filteredImage;
}
int main(int argc, char** argv ) {
Mat src;
src = imread( argv[1], 0 );
imwrite("original_image_grayscale.png", src);
if ( !src.data )
{
printf("No image data \n");
return -1;
}
Mat filteredImageOpenCV;
bilateralFilter(src, filteredImageOpenCV, 5, 12.0, 16.0);
imwrite("filtered_image_OpenCV.png", filteredImageOpenCV);
Mat filteredImageOwn = bilateralFilterOwn(src, 5, 12.0, 16.0);
imwrite("filtered_image_own.png", filteredImageOwn);
return 0;
}