blur_c.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include "../tp2.h"
  5. #define M_PI 3.14159265358979323846
  6. #define DEBUG 0
  7. /**
  8. * Calculo la matriz de convulsión.
  9. * Hago el calculo de todos los componentes.
  10. * PRE: Esto asume que existen "r" pixeles para cada lado del pixel actual para hacer la cuenta
  11. + TODO: Hay que hacer free de la matriz
  12. */
  13. float* convulcion_matrix(float sigma, int r) {
  14. unsigned int contador = 0;
  15. unsigned int largo = 2*r + 1;
  16. float* conv_matrix = malloc(sizeof(float)*largo*largo);
  17. #if DEBUG
  18. printf("Sigma: %f | Radio: %d \n", sigma,r);
  19. #endif
  20. // Recorro cada pixel
  21. for (int y = -r; y <= r; y++) {
  22. for (int x = -r; x <= r; x++) {
  23. conv_matrix[contador] = (1 / (2*M_PI*sigma*sigma)) * exp(- (pow(x,2)+pow(y,2))/(2*sigma*sigma));
  24. #if DEBUG
  25. printf("%.8f\t", conv_matrix[contador]);
  26. #endif
  27. contador++;
  28. }
  29. #if DEBUG
  30. printf("\n");
  31. #endif
  32. }
  33. return conv_matrix;
  34. }
  35. void blur_c(unsigned char *src, unsigned char *dst, int cols, int filas, float sigma, int r) {
  36. unsigned char (*src_matrix)[cols*4] = (unsigned char (*)[cols*4]) src;
  37. unsigned char (*dst_matrix)[cols*4] = (unsigned char (*)[cols*4]) dst;
  38. float* mc = convulcion_matrix(sigma, r);
  39. float tmp[3];
  40. int i, j, x, y, matPos;
  41. // Recorro la imagen, ignoro los bordes de tamaño R
  42. for(i=r; i<filas-r; i++) {
  43. for(j=r; j<cols-r; j++) {
  44. tmp[0]=0; tmp[1]=0; tmp[2]=0; matPos = 0;
  45. // Recorro la submatriz que le corresponde al pixel actual y hago las multiplicaciones
  46. for(y=-r; y<=r; y++) {
  47. for(x=-r; x<=r; x++) {
  48. tmp[0]+=src_matrix[i+y][4*(x+j)+0] * mc[matPos];
  49. tmp[1]+=src_matrix[i+y][4*(x+j)+1] * mc[matPos];
  50. tmp[2]+=src_matrix[i+y][4*(x+j)+2] * mc[matPos];
  51. matPos++; // Aumento una posición en la matriz de convulsion
  52. }
  53. }
  54. dst_matrix[i][4*j+0]=(int)tmp[0]; // B
  55. dst_matrix[i][4*j+1]=(int)tmp[1]; // G
  56. dst_matrix[i][4*j+2]=(int)tmp[2]; // R
  57. dst_matrix[i][4*j+3]=255; // A
  58. }
  59. }
  60. // Borro la matriz de convulsion
  61. free(mc);
  62. }