blur_c.c 2.3 KB

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