source: libpipi/trunk/pipi/filter/blur.c @ 2606

Revision 2606, 2.4 KB checked in by sam, 5 years ago (diff)
  • blur.c: fix overflow errors.
Line 
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/*
16 * blur.c: blur functions
17 */
18
19#include "config.h"
20#include "common.h"
21
22#include <stdlib.h>
23#include <stdio.h>
24#include <string.h>
25#include <math.h>
26
27#include "pipi.h"
28#include "pipi_internals.h"
29
30pipi_image_t *pipi_gaussian_blur(pipi_image_t *src, float radius)
31{
32    pipi_image_t *dst;
33    pipi_pixels_t *srcp, *dstp;
34    float *srcdata, *dstdata;
35    double *kernel;
36    double K, L;
37    int x, y, i, j, w, h, kr, kw;
38
39    w = src->w;
40    h = src->h;
41
42    srcp = pipi_getpixels(src, PIPI_PIXELS_RGBA_F);
43    srcdata = (float *)srcp->pixels;
44
45    dst = pipi_new(w, h);
46    dstp = pipi_getpixels(dst, PIPI_PIXELS_RGBA_F);
47    dstdata = (float *)dstp->pixels;
48
49    kr = (int)(3. * radius + 0.99999);
50    kw = 2 * kr + 1;
51    K = 1. / (2. * M_PI * radius * radius);
52    L = -1. / (2. * radius * radius);
53
54    kernel = malloc(kw * kw * sizeof(double));
55    for(j = -kr; j <= kr; j++)
56        for(i = -kr; i <= kr; i++)
57            kernel[(j + kr) * kw + (i + kr)] = exp(L * (i * i + j * j)) * K;
58
59    for(y = 0; y < h; y++)
60    {
61        for(x = 0; x < w; x++)
62        {
63            double R = 0., G = 0., B = 0., t = 0.;
64            int x2, y2;
65
66            for(j = -kr; j <= kr; j++)
67            {
68                y2 = y + j;
69                if(y2 < 0) y2 = 0;
70                else if(y2 >= h) y2 = h - 1;
71
72                for(i = -kr; i <= kr; i++)
73                {
74                    double f = kernel[(j + kr) * kw + (i + kr)];
75
76                    x2 = x + i;
77                    if(x2 < 0) x2 = 0;
78                    else if(x2 >= w) x2 = w - 1;
79
80                    R += f * srcdata[(y2 * w + x2) * 4];
81                    G += f * srcdata[(y2 * w + x2) * 4 + 1];
82                    B += f * srcdata[(y2 * w + x2) * 4 + 2];
83                    t += f;
84                }
85            }
86
87            dstdata[(y * w + x) * 4] = R / t;
88            dstdata[(y * w + x) * 4 + 1] = G / t;
89            dstdata[(y * w + x) * 4 + 2] = B / t;
90        }
91    }
92
93    return dst;
94}
95
Note: See TracBrowser for help on using the repository browser.