blur_c.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. // Por cada pixel obtengo la sub-matriz de convulsion para cada componente
  24. conv_matrix[contador] = (1 / (2*M_PI*sigma*sigma)) * exp(- (pow(x,2)+pow(y,2))/(2*sigma*sigma));
  25. #if DEBUG
  26. printf("%.8f\t", conv_matrix[contador]);
  27. #endif
  28. contador++;
  29. }
  30. #if DEBUG
  31. printf("\n");
  32. #endif
  33. }
  34. return conv_matrix;
  35. }
  36. void blur_c(unsigned char *src, unsigned char *dst, int cols, int filas, float sigma, int r) {
  37. unsigned char (*src_matrix)[cols*4] = (unsigned char (*)[cols*4]) src;
  38. unsigned char (*dst_matrix)[cols*4] = (unsigned char (*)[cols*4]) dst;
  39. float* mc = convulcion_matrix(sigma, r);
  40. float tmp[3];
  41. int i, j, x, y, matPos;
  42. // Recorro la imagen, ignoro los bordes de tamaño R
  43. for(i=r; i<filas-r; i++) {
  44. for(j=r; j<cols-r; j++) {
  45. tmp[0]=0; tmp[1]=0; tmp[2]=0; matPos = 0;
  46. // Recorro la submatriz que le corresponde al pixel actual y hago las multiplicaciones
  47. for(y=-r; y<=r; y++) {
  48. for(x=-r; x<=r; x++) {
  49. tmp[0]+=src_matrix[i+y][4*(x+j)+0] * mc[matPos];
  50. tmp[1]+=src_matrix[i+y][4*(x+j)+1] * mc[matPos];
  51. tmp[2]+=src_matrix[i+y][4*(x+j)+2] * mc[matPos];
  52. matPos++; // Aumento una posición en la matriz de convulsion
  53. }
  54. }
  55. dst_matrix[i][4*j+0]=(int)tmp[0]; // B
  56. dst_matrix[i][4*j+1]=(int)tmp[1]; // G
  57. dst_matrix[i][4*j+2]=(int)tmp[2]; // R
  58. dst_matrix[i][4*j+3]=255; // A
  59. }
  60. }
  61. // Borro la matriz de convulsion
  62. free(mc);
  63. }