Coverage Report

Created: 2026-12-01 07:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libvips/libvips/histogram/hist_local.c
Line
Count
Source
1
/* local histogram equalisation
2
 *
3
 * Copyright: 1991, N. Dessipris
4
 *
5
 * Author: N. Dessipris
6
 * Written on: 24/10/1991
7
 * Modified on :
8
 * 25/1/96 JC
9
 *  - rewritten, adapting im_spcor()
10
 *  - correct result, 2x faster, partial, simpler, better arg checking
11
 * 8/7/04
12
 *  - expand input rather than output with new im_embed() mode
13
 *  - _raw() output is one pixel larger
14
 *  - sets Xoffset/Yoffset
15
 * 23/6/08
16
 *  - check for window too small as well
17
 * 25/3/10
18
 *  - gtkdoc
19
 *  - small cleanups
20
 * 5/9/13
21
 *  - redo as a class
22
 * 9/9/13
23
 *  - any number of bands
24
 * 20/1/17
25
 *  - add contrast limit
26
 *  - sum to <= target, not < target, since cumulative hists include the
27
 *    current value
28
 *  - scale result by 255, not 256, to avoid overflow
29
 *  - off by 1 fix for odd window widths
30
 */
31
32
/*
33
34
  This file is part of VIPS.
35
36
  VIPS is free software; you can redistribute it and/or modify
37
  it under the terms of the GNU Lesser General Public License as published by
38
  the Free Software Foundation; either version 2 of the License, or
39
  (at your option) any later version.
40
41
  This program is distributed in the hope that it will be useful,
42
  but WITHOUT ANY WARRANTY; without even the implied warranty of
43
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
44
  GNU Lesser General Public License for more details.
45
46
  You should have received a copy of the GNU Lesser General Public License
47
  along with this program; if not, write to the Free Software
48
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
49
  02110-1301  USA
50
51
 */
52
53
/*
54
55
  These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
56
57
 */
58
59
#ifdef HAVE_CONFIG_H
60
#include <config.h>
61
#endif /*HAVE_CONFIG_H*/
62
#include <glib/gi18n-lib.h>
63
64
#include <stdio.h>
65
#include <stdlib.h>
66
#include <string.h>
67
68
#include <vips/vips.h>
69
#include <vips/internal.h>
70
71
typedef struct _VipsHistLocal {
72
  VipsOperation parent_instance;
73
74
  VipsImage *in;
75
  VipsImage *out;
76
77
  int width;
78
  int height;
79
80
  int max_slope;
81
82
} VipsHistLocal;
83
84
typedef VipsOperationClass VipsHistLocalClass;
85
86
40
G_DEFINE_TYPE(VipsHistLocal, vips_hist_local, VIPS_TYPE_OPERATION);
87
40
88
40
/* Our sequence value: the region this sequence is using, and local stats.
89
40
 */
90
40
typedef struct {
91
40
  VipsRegion *ir; /* Input region */
92
40
93
40
  /* A 256-element hist for every band.
94
40
   */
95
40
  unsigned int **hist;
96
40
} VipsHistLocalSequence;
97
40
98
40
static int
99
40
vips_hist_local_stop(void *vseq, void *a, void *b)
100
40
{
101
15
  VipsHistLocalSequence *seq = (VipsHistLocalSequence *) vseq;
102
15
  VipsImage *in = (VipsImage *) a;
103
104
15
  VIPS_UNREF(seq->ir);
105
106
15
  if (seq->hist &&
107
15
    in)
108
48
    for (int i = 0; i < in->Bands; i++)
109
33
      VIPS_FREE(seq->hist[i]);
110
15
  VIPS_FREE(seq->hist);
111
15
  VIPS_FREE(seq);
112
113
15
  return 0;
114
15
}
115
116
static void *
117
vips_hist_local_start(VipsImage *out, void *a, void *b)
118
15
{
119
15
  VipsImage *in = (VipsImage *) a;
120
15
  VipsHistLocalSequence *seq;
121
122
15
  if (!(seq = VIPS_NEW(NULL, VipsHistLocalSequence)))
123
0
    return NULL;
124
15
  seq->ir = NULL;
125
15
  seq->hist = NULL;
126
127
15
  if (!(seq->ir = vips_region_new(in)) ||
128
15
    !(seq->hist = VIPS_ARRAY(NULL, in->Bands, unsigned int *))) {
129
0
    vips_hist_local_stop(seq, NULL, NULL);
130
0
    return NULL;
131
0
  }
132
133
48
  for (int i = 0; i < in->Bands; i++)
134
33
    if (!(seq->hist[i] = VIPS_ARRAY(NULL, 256, unsigned int))) {
135
0
      vips_hist_local_stop(seq, NULL, NULL);
136
0
      return NULL;
137
0
    }
138
139
15
  return seq;
140
15
}
141
142
static int
143
vips_hist_local_generate(VipsRegion *out_region,
144
  void *vseq, void *a, void *b, gboolean *stop)
145
15
{
146
15
  VipsHistLocalSequence *seq = (VipsHistLocalSequence *) vseq;
147
15
  VipsImage *in = (VipsImage *) a;
148
15
  const VipsHistLocal *local = (VipsHistLocal *) b;
149
15
  VipsRect *r = &out_region->valid;
150
15
  const int bands = in->Bands;
151
15
  const int max_slope = local->max_slope;
152
153
15
  VipsRect s;
154
15
  int lsk;
155
15
  int centre; /* Offset to move to centre of window */
156
157
  /* Prepare the section of the input image we need. A little larger
158
   * than the section of the output image we are producing.
159
   */
160
15
  s = *r;
161
15
  s.width += local->width;
162
15
  s.height += local->height - 1;
163
15
  if (vips_region_prepare(seq->ir, &s))
164
1
    return -1;
165
166
14
  lsk = VIPS_REGION_LSKIP(seq->ir);
167
14
  centre = lsk * (local->height / 2) + bands * (local->width / 2);
168
169
160
  for (int y = 0; y < r->height; y++) {
170
    /* Get input and output pointers for this line.
171
     */
172
146
    VipsPel *restrict p =
173
146
      VIPS_REGION_ADDR(seq->ir, r->left, r->top + y);
174
146
    VipsPel *restrict q =
175
146
      VIPS_REGION_ADDR(out_region, r->left, r->top + y);
176
177
146
    VipsPel *restrict p1;
178
179
    /* Find histogram for the start of this line.
180
     */
181
520
    for (int b = 0; b < bands; b++)
182
374
      memset(seq->hist[b], 0, 256 * sizeof(unsigned int));
183
146
    p1 = p;
184
1.15k
    for (int j = 0; j < local->height; j++) {
185
1.01k
      int i;
186
187
1.01k
      i = 0;
188
8.62k
      for (int x = 0; x < local->width; x++)
189
29.5k
        for (int b = 0; b < bands; b++, i++)
190
21.9k
          seq->hist[b][p1[i]] += 1;
191
192
1.01k
      p1 += lsk;
193
1.01k
    }
194
195
    /* Loop for output pels.
196
     */
197
2.19k
    for (int x = 0; x < r->width; x++) {
198
7.71k
      for (int b = 0; b < bands; b++) {
199
        /* Sum histogram up to current pel.
200
         */
201
5.66k
        unsigned int *restrict hist = seq->hist[b];
202
5.66k
        const int target = p[centre + b];
203
204
5.66k
        int sum;
205
206
5.66k
        sum = 0;
207
208
        /* For CLAHE we need to limit the height of the hist to limit
209
         * the amount we boost the contrast by.
210
         */
211
5.66k
        if (max_slope > 0) {
212
0
          int i;
213
0
          int sum_over;
214
215
0
          sum_over = 0;
216
217
          /* Must be <= target, since a cum hist always includes
218
           * the current element.
219
           */
220
0
          for (i = 0; i <= target; i++) {
221
0
            if (hist[i] > max_slope) {
222
0
              sum_over += hist[i] - max_slope;
223
0
              sum += max_slope;
224
0
            }
225
0
            else
226
0
              sum += hist[i];
227
0
          }
228
229
0
          for (; i < 256; i++) {
230
0
            if (hist[i] > max_slope)
231
0
              sum_over += hist[i] - max_slope;
232
0
          }
233
234
          /* The extra clipped off bit from the top of the hist is
235
           * spread over all bins equally, then summed to target.
236
           */
237
0
          sum += (target + 1) * sum_over / 256;
238
0
        }
239
5.66k
        else {
240
5.66k
          sum = 0;
241
701k
          for (int i = 0; i <= target; i++)
242
696k
            sum += hist[i];
243
5.66k
        }
244
245
        /* This can't overflow, even in contrast-limited mode.
246
         *
247
         * Scale by 255, not 256, or we'll get overflow.
248
         */
249
5.66k
        q[b] = 255 * sum / (local->width * local->height);
250
251
        /* Adapt histogram -- remove the pels from the left hand column,
252
         * add in pels for a new right-hand column.
253
         */
254
5.66k
        const int next = bands * local->width;
255
5.66k
        p1 = p + b;
256
49.9k
        for (int j = 0; j < local->height; j++) {
257
44.2k
          hist[p1[0]] -= 1;
258
44.2k
          hist[p1[next]] += 1;
259
260
44.2k
          p1 += lsk;
261
44.2k
        }
262
5.66k
      }
263
264
2.04k
      p += bands;
265
2.04k
      q += bands;
266
2.04k
    }
267
146
  }
268
269
14
  return 0;
270
15
}
271
272
static int
273
vips_hist_local_build(VipsObject *object)
274
18
{
275
18
  VipsObjectClass *class = VIPS_OBJECT_GET_CLASS(object);
276
18
  VipsHistLocal *local = (VipsHistLocal *) object;
277
18
  VipsImage **t = (VipsImage **) vips_object_local_array(object, 3);
278
279
18
  VipsImage *in;
280
281
18
  if (VIPS_OBJECT_CLASS(vips_hist_local_parent_class)->build(object))
282
0
    return -1;
283
284
18
  in = local->in;
285
286
18
  if (vips_image_decode(in, &t[0]))
287
0
    return -1;
288
18
  in = t[0];
289
290
18
  if (vips_check_format(class->nickname, in, VIPS_FORMAT_UCHAR))
291
1
    return -1;
292
293
17
  if (local->width > in->Xsize ||
294
16
    local->height > in->Ysize) {
295
2
    vips_error(class->nickname, "%s", _("window too large"));
296
2
    return -1;
297
2
  }
298
299
  /* Expand the input.
300
   */
301
15
  if (vips_embed(in, &t[1],
302
15
      local->width / 2, local->height / 2,
303
15
      in->Xsize + local->width, in->Ysize + local->height - 1,
304
15
      "extend", VIPS_EXTEND_MIRROR,
305
15
      NULL))
306
0
    return -1;
307
15
  in = t[1];
308
309
15
  g_object_set(object, "out", vips_image_new(), NULL);
310
311
  /* Set demand hints. FATSTRIP is good for us, as THINSTRIP will cause
312
   * too many recalculations on overlaps.
313
   */
314
15
  if (vips_image_pipelinev(local->out,
315
15
      VIPS_DEMAND_STYLE_FATSTRIP, in, NULL))
316
0
    return -1;
317
15
  local->out->Xsize -= local->width;
318
15
  local->out->Ysize -= local->height - 1;
319
320
15
  if (vips_image_generate(local->out,
321
15
      vips_hist_local_start,
322
15
      vips_hist_local_generate,
323
15
      vips_hist_local_stop,
324
15
      in, local))
325
0
    return -1;
326
327
15
  local->out->Xoffset = 0;
328
15
  local->out->Yoffset = 0;
329
330
15
  vips_reorder_margin_hint(local->out, local->width * local->height);
331
332
15
  return 0;
333
15
}
334
335
static void
336
vips_hist_local_class_init(VipsHistLocalClass *class)
337
20
{
338
20
  GObjectClass *gobject_class = G_OBJECT_CLASS(class);
339
20
  VipsObjectClass *object_class = (VipsObjectClass *) class;
340
20
  VipsOperationClass *operation_class = VIPS_OPERATION_CLASS(class);
341
342
20
  gobject_class->set_property = vips_object_set_property;
343
20
  gobject_class->get_property = vips_object_get_property;
344
345
20
  object_class->nickname = "hist_local";
346
20
  object_class->description = _("local histogram equalisation");
347
20
  object_class->build = vips_hist_local_build;
348
349
20
  operation_class->flags = VIPS_OPERATION_SEQUENTIAL;
350
351
20
  VIPS_ARG_IMAGE(class, "in", 1,
352
20
    _("Input"),
353
20
    _("Input image"),
354
20
    VIPS_ARGUMENT_REQUIRED_INPUT,
355
20
    G_STRUCT_OFFSET(VipsHistLocal, in));
356
357
20
  VIPS_ARG_IMAGE(class, "out", 2,
358
20
    _("Output"),
359
20
    _("Output image"),
360
20
    VIPS_ARGUMENT_REQUIRED_OUTPUT,
361
20
    G_STRUCT_OFFSET(VipsHistLocal, out));
362
363
20
  VIPS_ARG_INT(class, "width", 4,
364
20
    _("Width"),
365
20
    _("Window width in pixels"),
366
20
    VIPS_ARGUMENT_REQUIRED_INPUT,
367
20
    G_STRUCT_OFFSET(VipsHistLocal, width),
368
20
    1, VIPS_MAX_COORD, 1);
369
370
20
  VIPS_ARG_INT(class, "height", 5,
371
20
    _("Height"),
372
20
    _("Window height in pixels"),
373
20
    VIPS_ARGUMENT_REQUIRED_INPUT,
374
20
    G_STRUCT_OFFSET(VipsHistLocal, height),
375
20
    1, VIPS_MAX_COORD, 1);
376
377
20
  VIPS_ARG_INT(class, "max_slope", 6,
378
20
    _("Max slope"),
379
20
    _("Maximum slope (CLAHE)"),
380
20
    VIPS_ARGUMENT_OPTIONAL_INPUT,
381
20
    G_STRUCT_OFFSET(VipsHistLocal, max_slope),
382
20
    0, 100, 0);
383
20
}
384
385
static void
386
vips_hist_local_init(VipsHistLocal *local)
387
20
{
388
20
}
389
390
/**
391
 * vips_hist_local: (method)
392
 * @in: input image
393
 * @out: (out): output image
394
 * @width: width of region
395
 * @height: height of region
396
 * @...: `NULL`-terminated list of optional named arguments
397
 *
398
 * Performs local histogram equalisation on @in using a
399
 * window of size @width by @height centered on the input pixel.
400
 *
401
 * The output image is the same size as the input image. The edge pixels are
402
 * created by mirroring the input image outwards.
403
 *
404
 * If @max_slope is greater than 0, it sets the maximum value for the slope of
405
 * the cumulative histogram, that is, the maximum brightening that is
406
 * performed. A value of 3 is often used. Local histogram equalization with
407
 * contrast limiting is usually called CLAHE.
408
 *
409
 * ::: tip "Optional arguments"
410
 *     * @max_slope: `gint`, maximum brightening
411
 *
412
 * ::: seealso
413
 *     [method@Image.hist_equal].
414
 *
415
 * Returns: 0 on success, -1 on error
416
 */
417
int
418
vips_hist_local(VipsImage *in, VipsImage **out, int width, int height, ...)
419
0
{
420
0
  va_list ap;
421
0
  int result;
422
423
0
  va_start(ap, height);
424
0
  result = vips_call_split("hist_local", ap, in, out, width, height);
425
0
  va_end(ap);
426
427
0
  return result;
428
0
}