89 lines
2.3 KiB

  1. /*
  2. * libpipi Proper image processing implementation library
  3. * Copyright (c) 2004-2008 Sam Hocevar <sam@zoy.org>
  4. * All Rights Reserved
  5. *
  6. * $Id$
  7. *
  8. * This library is free software. It comes without any warranty, to
  9. * the extent permitted by applicable law. You can redistribute it
  10. * and/or modify it under the terms of the Do What The Fuck You Want
  11. * To Public License, Version 2, as published by Sam Hocevar. See
  12. * http://sam.zoy.org/wtfpl/COPYING for more details.
  13. */
  14. /*
  15. * blur.c: blur functions
  16. */
  17. #include "config.h"
  18. #include "common.h"
  19. #include <stdlib.h>
  20. #include <stdio.h>
  21. #include <string.h>
  22. #include <math.h>
  23. #include "pipi.h"
  24. #include "pipi_internals.h"
  25. pipi_image_t *pipi_gaussian_blur(pipi_image_t *src, float radius)
  26. {
  27. pipi_image_t *dst;
  28. pipi_pixels_t *srcp, *dstp;
  29. float *srcdata, *dstdata;
  30. double *kernel;
  31. double K, L, t = 0.;
  32. int x, y, i, j, w, h, kr, kw;
  33. w = src->w;
  34. h = src->h;
  35. srcp = pipi_getpixels(src, PIPI_PIXELS_RGBA_F);
  36. srcdata = (float *)srcp->pixels;
  37. dst = pipi_new(w, h);
  38. dstp = pipi_getpixels(dst, PIPI_PIXELS_RGBA_F);
  39. dstdata = (float *)dstp->pixels;
  40. kr = (int)(3. * radius + 0.99999);
  41. kw = 2 * kr + 1;
  42. K = 1. / (2. * M_PI * radius * radius);
  43. L = -1. / (2. * radius * radius);
  44. kernel = malloc(kw * kw * sizeof(double));
  45. for(j = -kr; j <= kr; j++)
  46. for(i = -kr; i <= kr; i++)
  47. t += kernel[(j + kr) * kw + (i + kr)]
  48. = exp(L * (i * i + j * j)) * K;
  49. for(j = -kr; j <= kr; j++)
  50. for(i = -kr; i <= kr; i++)
  51. kernel[(j + kr) * kw + (i + kr)] /= t;
  52. for(y = 0; y < h; y++)
  53. {
  54. for(x = 0; x < w; x++)
  55. {
  56. double R = 0., G = 0., B = 0.;
  57. for(j = -kr; j <= kr; j++)
  58. for(i = -kr; i <= kr; i++)
  59. {
  60. double f = kernel[(j + kr) * kw + (i + kr)];
  61. R += f * srcdata[((y + j) * w + x + i) * 4];
  62. G += f * srcdata[((y + j) * w + x + i) * 4 + 1];
  63. B += f * srcdata[((y + j) * w + x + i) * 4 + 2];
  64. }
  65. dstdata[(y * w + x) * 4] = R;
  66. dstdata[(y * w + x) * 4 + 1] = G;
  67. dstdata[(y * w + x) * 4 + 2] = B;
  68. }
  69. }
  70. return dst;
  71. }