113 lines
2.9 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. * convolution.c: generic convolution 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_convolution(pipi_image_t *src, int m, int n, double mat[])
  26. {
  27. pipi_image_t *dst;
  28. pipi_pixels_t *srcp, *dstp;
  29. float *srcdata, *dstdata;
  30. int x, y, i, j, w, h, gray;
  31. w = src->w;
  32. h = src->h;
  33. gray = (src->last_modified == PIPI_PIXELS_Y_F);
  34. srcp = gray ? pipi_getpixels(src, PIPI_PIXELS_Y_F)
  35. : pipi_getpixels(src, PIPI_PIXELS_RGBA_F);
  36. srcdata = (float *)srcp->pixels;
  37. dst = pipi_new(w, h);
  38. dstp = gray ? pipi_getpixels(dst, PIPI_PIXELS_Y_F)
  39. : pipi_getpixels(dst, PIPI_PIXELS_RGBA_F);
  40. dstdata = (float *)dstp->pixels;
  41. for(y = 0; y < h; y++)
  42. {
  43. for(x = 0; x < w; x++)
  44. {
  45. if(gray)
  46. {
  47. double Y = 0.;
  48. int x2, y2;
  49. for(j = 0; j < n; j++)
  50. {
  51. y2 = y + j - n / 2;
  52. if(y2 < 0) y2 = 0;
  53. else if(y2 >= h) y2 = h - 1;
  54. for(i = 0; i < m; i++)
  55. {
  56. x2 = x + i;
  57. if(x2 < 0) x2 = 0;
  58. else if(x2 >= w) x2 = w - 1;
  59. Y += mat[j * m + i] * srcdata[y * w + x2];
  60. }
  61. }
  62. dstdata[y * w + x] = Y;
  63. }
  64. else
  65. {
  66. double R = 0., G = 0., B = 0.;
  67. int x2, y2, off = 4 * (y * w + x);
  68. for(j = 0; j < n; j++)
  69. {
  70. y2 = y + j - n / 2;
  71. if(y2 < 0) y2 = 0;
  72. else if(y2 >= h) y2 = h - 1;
  73. for(i = 0; i < m; i++)
  74. {
  75. double f = mat[j * m + i];
  76. x2 = x + i;
  77. if(x2 < 0) x2 = 0;
  78. else if(x2 >= w) x2 = w - 1;
  79. R += f * srcdata[(y * w + x2) * 4];
  80. G += f * srcdata[(y * w + x2) * 4 + 1];
  81. B += f * srcdata[(y * w + x2) * 4 + 2];
  82. }
  83. }
  84. dstdata[off] = R;
  85. dstdata[off + 1] = G;
  86. dstdata[off + 2] = B;
  87. }
  88. }
  89. }
  90. return dst;
  91. }