Skip to content

Instantly share code, notes, and snippets.

@arthurcvm
Last active April 30, 2019 20:13
Show Gist options
  • Save arthurcvm/150f9eba97745c7225211949a8da4d9d to your computer and use it in GitHub Desktop.
Save arthurcvm/150f9eba97745c7225211949a8da4d9d to your computer and use it in GitHub Desktop.
Filtro gaussiana em imagem com ruído sal e pimenta
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <math.h>
#include <iostream>
using namespace cv;
using namespace std;
//Padrão usado para a configuração das matrizes(Métodos)
Mat convoluirGenerica(Mat& img, float **masc, int M, int N){
float output=0;
Mat resp = img.clone();
int m=(M-1)/2;
int n=(N-1)/2;
for (int x=0; x<img.rows;x++){
for (int y=0; y<img.cols; y++){
resp.at<uchar>(x,y) = 0;
}
}
for (int x=m; x<img.rows-m;x++){
for (int y=n; y<img.cols-n; y++) {
output=0;
for (int ml=-m; ml<=m; ml++){
for (int mc=-n; mc<=n; mc++) {
output += img.at<uchar>(x-mc,y-ml) * masc[mc+ m][ml+n];
if(output>255)
output=255;
if(output<0)
output=0;
}
}
resp.at<uchar>(x,y) = (int)output;
}
}
return (resp);
}
void criarGaussiano(float **mascara, int largura, int altura){
// adotando desvio padrão = 1,0
float sigma = 1.0;
float r, s = 2.0 * sigma * sigma;
// variável para somatório
float soma = 0.0;
// delimitadores para máscara simétrica com média em (0,0)
int m = (largura-1)/2;
int n = (altura-1)/2;
// geração dos valores da máscara
for (int x = -m; x <= m; x++) {
for (int y = -n; y <= n; y++) {
r = sqrt(x * x + y * y);
mascara[x + m][y + n] = (exp(-(r * r) / s)) / (M_PI * s);
soma += mascara[x + m][y + n];
}
}
// normalizando a máscara
for (int i = 0; i < largura; ++i)
for (int j = 0; j < altura; ++j)
mascara[i][j] /= soma;
}
Mat filtroGauss(Mat img, int x, int y){
Mat processada = img.clone();
// Cria dinamicamente uma matriz com as dimenções passadas por parametro
float **Kernel;
Kernel = (float**) malloc (x * sizeof(float*) );
for (int i=0; i<x; i++){
Kernel[i] = (float*) malloc (y * sizeof(float) );
}
criarGaussiano(Kernel, x, y); // Atribuição de valores a mascara
processada = convoluirGenerica(img, Kernel, x, y); // Processamento da imagem
return processada;
}
int main(){
Mat img = imread("/home/arthurcvm/final/fft/img.jpeg", 0);
Mat img2;
img2 = filtroGauss(img, 20, 20);
namedWindow("tela1");namedWindow("tela2");
imshow("tela1",img);imshow("tela2",img2);
waitKey(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment