blur_c.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <math.h>
  4. #define M_PI 3.14159265358979323846
  5. #include "../tp2.h"
  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. unsigned int diff = largo+ 4-(largo % 4);
  17. unsigned int tam = diff*largo;
  18. float* conv_matrix = malloc(sizeof(float)*tam);
  19. #if DEBUG
  20. printf("Sigma: %f | Radio: %d \n", sigma,r);
  21. #endif
  22. // Recorro cada pixel
  23. for (int y = -r; y <= r; y++) {
  24. for (int x = -r; x <= r+1; x++) {
  25. // Por cada pixel obtengo la sub-matriz de convulsion para cada componente
  26. if (x==r+1) { //Con esta idea, la matriz siempre tiene mult de 4 columnas, son todas 0 entonces no me afecta
  27. conv_matrix[contador] = 0;
  28. } else {
  29. conv_matrix[contador] = (1 / (2*M_PI*sigma*sigma)) * exp(- (pow(x,2)+pow(y,2))/(2*sigma*sigma));
  30. }
  31. #if DEBUG
  32. printf("%.8f\t", conv_matrix[contador]);
  33. #endif
  34. contador++;
  35. }
  36. #if DEBUG
  37. printf("\n");
  38. #endif
  39. }
  40. return conv_matrix;
  41. }
  42. void blur_c(unsigned char *src, unsigned char *dst, int cols, int filas, float sigma, int r) {
  43. unsigned char (*src_matrix)[cols*4] = (unsigned char (*)[cols*4]) src;
  44. unsigned char (*dst_matrix)[cols*4] = (unsigned char (*)[cols*4]) dst;
  45. float* mc = convulcion_matrix(sigma, r);
  46. float tmp[3];
  47. int i, j, x, y, matPos;
  48. // Recorro la imagen, ignoro los bordes de tamaño R
  49. for(i=r; i<filas-r; i++) {
  50. for(j=r; j<cols-r; j++) {
  51. tmp[0]=0; tmp[1]=0; tmp[2]=0; matPos = 0;
  52. // Recorro la submatriz que le corresponde al pixel actual y hago las multiplicaciones
  53. for(y=-r; y<=r; y++) {
  54. for(x=-r; x<=r+1; x++) {
  55. //En C nunca veo la ultima posicion (0) de la matriz
  56. if (x<=r){
  57. tmp[0]+=src_matrix[i+y][4*(x+j)+0] * mc[matPos];
  58. tmp[1]+=src_matrix[i+y][4*(x+j)+1] * mc[matPos];
  59. tmp[2]+=src_matrix[i+y][4*(x+j)+2] * mc[matPos];
  60. }
  61. matPos++; // Aumento una posición en la matriz de convulsion
  62. }
  63. }
  64. dst_matrix[i][4*j+0]=(int)tmp[0]; // B
  65. dst_matrix[i][4*j+1]=(int)tmp[1]; // G
  66. dst_matrix[i][4*j+2]=(int)tmp[2]; // R
  67. dst_matrix[i][4*j+3]=255; // A
  68. }
  69. }
  70. // Borro la matriz de convulsion
  71. free(mc);
  72. }