Coverage Report

Created: 2026-12-01 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libvips/libvips/morphology/rank.c
Line
Count
Source
1
/* Rank filter.
2
 *
3
 * Author: JC
4
 * Written on: 19/8/96
5
 * Modified on:
6
 * JC 20/8/96
7
 *  - now uses insert-sort rather than bubble-sort
8
 *  - now works for any non-complex type
9
 * JC 22/6/01
10
 *  - oops, sanity check on n wrong
11
 * JC 28/8/03
12
 *  - cleanups
13
 *  - better selection algorithm ... same speed for 3x3, about 3x faster
14
 *    for 5x5, faster still for larger windows
15
 *  - index from zero for consistency with other parts of vips
16
 * 7/4/04
17
 *  - now uses im_embed() with edge stretching on the input, not
18
 *    the output
19
 *  - sets Xoffset / Yoffset
20
 * 7/10/04
21
 *  - oops, im_embed() size was wrong
22
 * 10/11/10
23
 *  - cleanups
24
 *  - gtk-doc
25
 * 17/1/14
26
 *  - redone as a class
27
 * 12/11/16
28
 *  - oop, allow index == 0, thanks Rob
29
 * 12/1/21
30
 *  - add hist path for large windows on uchar images
31
 */
32
33
/*
34
35
  This file is part of VIPS.
36
37
  VIPS is free software; you can redistribute it and/or modify
38
  it under the terms of the GNU Lesser General Public License as published by
39
  the Free Software Foundation; either version 2 of the License, or
40
  (at your option) any later version.
41
42
  This program is distributed in the hope that it will be useful,
43
  but WITHOUT ANY WARRANTY; without even the implied warranty of
44
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
45
  GNU Lesser General Public License for more details.
46
47
  You should have received a copy of the GNU Lesser General Public License
48
  along with this program; if not, write to the Free Software
49
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
50
  02110-1301  USA
51
52
 */
53
54
/*
55
56
  These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
57
58
 */
59
60
#ifdef HAVE_CONFIG_H
61
#include <config.h>
62
#endif /*HAVE_CONFIG_H*/
63
#include <glib/gi18n-lib.h>
64
65
#include <stdio.h>
66
#include <stdlib.h>
67
#include <string.h>
68
#include <math.h>
69
70
#include <vips/vips.h>
71
#include <vips/internal.h>
72
73
#include "pmorphology.h"
74
75
typedef struct _VipsRank {
76
  VipsMorphology parent_instance;
77
78
  VipsImage *out;
79
80
  int width;
81
  int height;
82
  int index;
83
84
  int n;
85
86
  gboolean hist_path;
87
88
} VipsRank;
89
90
typedef VipsMorphologyClass VipsRankClass;
91
92
2
G_DEFINE_TYPE(VipsRank, vips_rank, VIPS_TYPE_MORPHOLOGY);
93
2
94
2
/* Sequence value: just the array we sort in.
95
2
 */
96
2
typedef struct {
97
2
  VipsRegion *ir;
98
2
99
2
  /* Sort array.
100
2
   */
101
2
  VipsPel *sort;
102
2
103
2
  /* For large uchar images, the sort histogram.
104
2
   */
105
2
  unsigned int **hist;
106
2
} VipsRankSequence;
107
2
108
2
static int
109
2
vips_rank_stop(void *vseq, void *a, void *b)
110
2
{
111
0
  VipsRankSequence *seq = (VipsRankSequence *) vseq;
112
0
  VipsImage *in = (VipsImage *) a;
113
114
0
  VIPS_UNREF(seq->ir);
115
0
  VIPS_FREE(seq->sort);
116
117
0
  if (seq->hist &&
118
0
    in)
119
0
    for (int i = 0; i < in->Bands; i++)
120
0
      VIPS_FREE(seq->hist[i]);
121
0
  VIPS_FREE(seq->hist);
122
0
  VIPS_FREE(seq);
123
124
0
  return 0;
125
0
}
126
127
static void *
128
vips_rank_start(VipsImage *out, void *a, void *b)
129
0
{
130
0
  VipsImage *in = (VipsImage *) a;
131
0
  VipsRank *rank = (VipsRank *) b;
132
0
  VipsRankSequence *seq;
133
134
0
  if (!(seq = VIPS_NEW(NULL, VipsRankSequence)))
135
0
    return NULL;
136
0
  seq->ir = NULL;
137
0
  seq->sort = NULL;
138
0
  seq->hist = NULL;
139
140
0
  seq->ir = vips_region_new(in);
141
0
  if (!(seq->sort = VIPS_ARRAY(NULL,
142
0
        VIPS_IMAGE_SIZEOF_ELEMENT(in) * rank->n, VipsPel))) {
143
0
    vips_rank_stop(seq, in, rank);
144
0
    return NULL;
145
0
  }
146
147
0
  if (rank->hist_path) {
148
0
    if (!(seq->hist = VIPS_ARRAY(NULL, in->Bands, unsigned int *))) {
149
0
      vips_rank_stop(seq, in, rank);
150
0
      return NULL;
151
0
    }
152
153
0
    for (int i = 0; i < in->Bands; i++)
154
0
      if (!(seq->hist[i] = VIPS_ARRAY(NULL, 256, unsigned int))) {
155
0
        vips_rank_stop(seq, in, rank);
156
0
        return NULL;
157
0
      }
158
0
  }
159
160
0
  return (void *) seq;
161
0
}
162
163
/* Histogram path for large uchar ranks.
164
 */
165
static void
166
vips_rank_generate_uchar(VipsRegion *out_region,
167
  VipsRankSequence *seq, VipsRank *rank, int y)
168
0
{
169
0
  VipsImage *in = seq->ir->im;
170
0
  VipsRect *r = &out_region->valid;
171
0
  const int bands = in->Bands;
172
0
  const int lsk = VIPS_REGION_LSKIP(seq->ir);
173
174
  /* Get input and output pointers for this line.
175
   */
176
0
  VipsPel *restrict p = VIPS_REGION_ADDR(seq->ir, r->left, r->top + y);
177
0
  VipsPel *restrict q = VIPS_REGION_ADDR(out_region, r->left, r->top + y);
178
179
0
  VipsPel *restrict p1;
180
181
  /* Find histogram for the first output pixel.
182
   */
183
0
  for (int b = 0; b < bands; b++)
184
0
    memset(seq->hist[b], 0, 256 * sizeof(unsigned int));
185
0
  p1 = p;
186
0
  for (int j = 0; j < rank->height; j++) {
187
0
    int i;
188
189
0
    i = 0;
190
0
    for (int x = 0; x < rank->width; x++)
191
0
      for (int b = 0; b < bands; b++, i++)
192
0
        seq->hist[b][p1[i]] += 1;
193
194
0
    p1 += lsk;
195
0
  }
196
197
  /* Loop for output pels.
198
   */
199
0
  for (int x = 0; x < r->width; x++) {
200
0
    for (int b = 0; b < bands; b++) {
201
      /* Calculate cumulative histogram -- the value is the
202
       * index at which we pass the rank.
203
       */
204
0
      unsigned int *restrict hist = seq->hist[b];
205
206
0
      int sum;
207
0
      int value;
208
0
      sum = 0;
209
0
      for (value = 0; value < 256; value++) {
210
0
        sum += hist[value];
211
0
        if (sum > rank->index)
212
0
          break;
213
0
      }
214
0
      q[b] = value;
215
216
      /* Adapt histogram -- remove the pels from the left hand column,
217
       * add in pels for a new right-hand column.
218
       */
219
0
      const int next = bands * rank->width;
220
0
      p1 = p + b;
221
0
      for (int j = 0; j < rank->height; j++) {
222
0
        hist[p1[0]] -= 1;
223
0
        hist[p1[next]] += 1;
224
225
0
        p1 += lsk;
226
0
      }
227
0
    }
228
229
0
    p += bands;
230
0
    q += bands;
231
0
  }
232
0
}
233
234
/* Inner loop for select-sorting TYPE.
235
 */
236
#define LOOP_SELECT(TYPE) \
237
0
  { \
238
0
    TYPE *q = (TYPE *) VIPS_REGION_ADDR(out_region, r->left, r->top + y); \
239
0
    TYPE *p = (TYPE *) VIPS_REGION_ADDR(ir, r->left, r->top + y); \
240
0
    TYPE *sort = (TYPE *) seq->sort; \
241
0
    TYPE a; \
242
0
\
243
0
    for (x = 0; x < sz; x++) { \
244
0
      TYPE *d = p + x; \
245
0
\
246
0
      /* Copy window into sort[]. \
247
0
       */ \
248
0
      for (k = 0, j = 0; j < rank->height; j++) { \
249
0
        for (i = 0; i < eaw; i += bands, k++) \
250
0
          sort[k] = d[i]; \
251
0
        d += ls; \
252
0
      } \
253
0
\
254
0
      /* Rearrange sort[] to make the index-th element the index-th \
255
0
       * smallest, adapted from Numerical Recipes in C. \
256
0
       */ \
257
0
      lower = 0; /* Range we know the result lies in */ \
258
0
      upper = rank->n - 1; \
259
0
      for (;;) { \
260
0
        if (upper - lower < 2) { \
261
0
          /* 1 or 2 elements left. \
262
0
           */ \
263
0
          if (upper - lower == 1 && \
264
0
            sort[lower] > sort[upper]) \
265
0
            VIPS_SWAP(TYPE, \
266
0
              sort[lower], sort[upper]); \
267
0
          break; \
268
0
        } \
269
0
        else { \
270
0
          /* Pick mid-point of remaining elements. \
271
0
           */ \
272
0
          mid = (lower + upper) >> 1; \
273
0
\
274
0
          /* Sort lower/mid/upper elements, hold \
275
0
           * midpoint in sort[lower + 1] for \
276
0
           * partitioning. \
277
0
           */ \
278
0
          VIPS_SWAP(TYPE, sort[lower + 1], sort[mid]); \
279
0
          if (sort[lower] > sort[upper]) \
280
0
            VIPS_SWAP(TYPE, \
281
0
              sort[lower], sort[upper]); \
282
0
          if (sort[lower + 1] > sort[upper]) \
283
0
            VIPS_SWAP(TYPE, \
284
0
              sort[lower + 1], sort[upper]); \
285
0
          if (sort[lower] > sort[lower + 1]) \
286
0
            VIPS_SWAP(TYPE, \
287
0
              sort[lower], sort[lower + 1]); \
288
0
\
289
0
          i = lower + 1; \
290
0
          j = upper; \
291
0
          a = sort[lower + 1]; \
292
0
\
293
0
          for (;;) { \
294
0
            /* Search for out of order elements. \
295
0
             */ \
296
0
            do \
297
0
              i++; \
298
0
            while (sort[i] < a); \
299
0
            do \
300
0
              j--; \
301
0
            while (sort[j] > a); \
302
0
            if (j < i) \
303
0
              break; \
304
0
            VIPS_SWAP(TYPE, sort[i], sort[j]); \
305
0
          } \
306
0
\
307
0
          /* Replace mid element. \
308
0
           */ \
309
0
          sort[lower + 1] = sort[j]; \
310
0
          sort[j] = a; \
311
0
\
312
0
          /* Move to partition with the kth element. \
313
0
           */ \
314
0
          if (j >= rank->index) \
315
0
            upper = j - 1; \
316
0
          if (j <= rank->index) \
317
0
            lower = i; \
318
0
        } \
319
0
      } \
320
0
\
321
0
      q[x] = sort[rank->index]; \
322
0
    } \
323
0
  }
324
325
/* Loop for find max of window.
326
 */
327
#define LOOP_MAX(TYPE) \
328
0
  { \
329
0
    TYPE *q = (TYPE *) VIPS_REGION_ADDR(out_region, r->left, r->top + y); \
330
0
    TYPE *p = (TYPE *) VIPS_REGION_ADDR(ir, r->left, r->top + y); \
331
0
\
332
0
    for (x = 0; x < sz; x++) { \
333
0
      TYPE *d = &p[x]; \
334
0
      TYPE max; \
335
0
\
336
0
      max = *d; \
337
0
      for (j = 0; j < rank->height; j++) { \
338
0
        TYPE *e = d; \
339
0
\
340
0
        for (i = 0; i < rank->width; i++) { \
341
0
          if (*e > max) \
342
0
            max = *e; \
343
0
\
344
0
          e += bands; \
345
0
        } \
346
0
\
347
0
        d += ls; \
348
0
      } \
349
0
\
350
0
      q[x] = max; \
351
0
    } \
352
0
  }
353
354
/* Loop for find min of window.
355
 */
356
#define LOOP_MIN(TYPE) \
357
0
  { \
358
0
    TYPE *q = (TYPE *) VIPS_REGION_ADDR(out_region, r->left, r->top + y); \
359
0
    TYPE *p = (TYPE *) VIPS_REGION_ADDR(ir, r->left, r->top + y); \
360
0
\
361
0
    for (x = 0; x < sz; x++) { \
362
0
      TYPE *d = &p[x]; \
363
0
      TYPE min; \
364
0
\
365
0
      min = *d; \
366
0
      for (j = 0; j < rank->height; j++) { \
367
0
        TYPE *e = d; \
368
0
\
369
0
        for (i = 0; i < rank->width; i++) { \
370
0
          if (*e < min) \
371
0
            min = *e; \
372
0
\
373
0
          e += bands; \
374
0
        } \
375
0
\
376
0
        d += ls; \
377
0
      } \
378
0
\
379
0
      q[x] = min; \
380
0
    } \
381
0
  }
382
383
#define SWITCH(OPERATION) \
384
0
  switch (rank->out->BandFmt) { \
385
0
  case VIPS_FORMAT_UCHAR: \
386
0
    OPERATION(unsigned char); \
387
0
    break; \
388
0
  case VIPS_FORMAT_CHAR: \
389
0
    OPERATION(signed char); \
390
0
    break; \
391
0
  case VIPS_FORMAT_USHORT: \
392
0
    OPERATION(unsigned short); \
393
0
    break; \
394
0
  case VIPS_FORMAT_SHORT: \
395
0
    OPERATION(signed short); \
396
0
    break; \
397
0
  case VIPS_FORMAT_UINT: \
398
0
    OPERATION(unsigned int); \
399
0
    break; \
400
0
  case VIPS_FORMAT_INT: \
401
0
    OPERATION(signed int); \
402
0
    break; \
403
0
  case VIPS_FORMAT_FLOAT: \
404
0
    OPERATION(float); \
405
0
    break; \
406
0
  case VIPS_FORMAT_DOUBLE: \
407
0
    OPERATION(double); \
408
0
    break; \
409
0
\
410
0
  default: \
411
0
    g_assert_not_reached(); \
412
0
  }
413
414
static int
415
vips_rank_generate(VipsRegion *out_region,
416
  void *vseq, void *a, void *b, gboolean *stop)
417
0
{
418
0
  VipsRect *r = &out_region->valid;
419
0
  VipsRankSequence *seq = (VipsRankSequence *) vseq;
420
0
  VipsRegion *ir = seq->ir;
421
0
  VipsImage *in = (VipsImage *) a;
422
0
  VipsRank *rank = (VipsRank *) b;
423
0
  int bands = in->Bands;
424
0
  int eaw = rank->width * bands; /* elements across window */
425
0
  int sz = VIPS_REGION_N_ELEMENTS(out_region);
426
427
0
  VipsRect s;
428
0
  int ls;
429
430
0
  int x;
431
0
  int i, j, k;
432
0
  int upper, lower, mid;
433
434
  /* Prepare the section of the input image we need. A little larger
435
   * than the section of the output image we are producing.
436
   */
437
0
  s = *r;
438
0
  s.width += rank->width;
439
0
  s.height += rank->height - 1;
440
0
  if (vips_region_prepare(ir, &s))
441
0
    return -1;
442
0
  ls = VIPS_REGION_LSKIP(ir) / VIPS_IMAGE_SIZEOF_ELEMENT(in);
443
444
0
  for (int y = 0; y < r->height; y++) {
445
0
    if (rank->hist_path)
446
0
      vips_rank_generate_uchar(out_region, seq, rank, y);
447
0
    else if (rank->index == 0)
448
0
      SWITCH(LOOP_MIN)
449
0
    else if (rank->index == rank->n - 1)
450
0
      SWITCH(LOOP_MAX)
451
0
    else
452
0
      SWITCH(LOOP_SELECT)
453
0
  }
454
455
0
  return 0;
456
0
}
457
458
static int
459
vips_rank_build(VipsObject *object)
460
0
{
461
0
  VipsObjectClass *class = VIPS_OBJECT_GET_CLASS(object);
462
0
  VipsMorphology *morphology = VIPS_MORPHOLOGY(object);
463
0
  VipsRank *rank = (VipsRank *) object;
464
0
  VipsImage **t = (VipsImage **) vips_object_local_array(object, 3);
465
466
0
  VipsImage *in;
467
468
0
  if (VIPS_OBJECT_CLASS(vips_rank_parent_class)->build(object))
469
0
    return -1;
470
471
0
  in = morphology->in;
472
473
0
  if (vips_image_decode(in, &t[0]))
474
0
    return -1;
475
0
  in = t[0];
476
477
0
  if (vips_check_noncomplex(class->nickname, in))
478
0
    return -1;
479
0
  if (rank->width > in->Xsize ||
480
0
    rank->height > in->Ysize) {
481
0
    vips_error(class->nickname, "%s", _("window too large"));
482
0
    return -1;
483
0
  }
484
0
  rank->n = rank->width * rank->height;
485
0
  if (rank->index < 0 ||
486
0
    rank->index > rank->n - 1) {
487
0
    vips_error(class->nickname, "%s", _("index out of range"));
488
0
    return -1;
489
0
  }
490
491
  /* Enable the hist path if it'll probably help.
492
   */
493
0
  if (in->BandFmt == VIPS_FORMAT_UCHAR) {
494
    /* The hist path is always faster for windows larger than about
495
     * 10x10, and faster for >3x3 on the non-max/min case.
496
     */
497
0
    if (rank->n > 90)
498
0
      rank->hist_path = TRUE;
499
0
    else if (rank->n > 10 &&
500
0
      rank->index != 0 &&
501
0
      rank->index != rank->n - 1)
502
0
      rank->hist_path = TRUE;
503
0
  }
504
505
  /* Expand the input.
506
   */
507
0
  if (vips_embed(in, &t[1],
508
0
      rank->width / 2, rank->height / 2,
509
0
      in->Xsize + rank->width, in->Ysize + rank->height - 1,
510
0
      "extend", VIPS_EXTEND_COPY,
511
0
      NULL))
512
0
    return -1;
513
0
  in = t[1];
514
515
0
  g_object_set(object, "out", vips_image_new(), NULL);
516
517
  /* Set demand hints. FATSTRIP is good for us, as THINSTRIP will cause
518
   * too many recalculations on overlaps.
519
   */
520
0
  if (vips_image_pipelinev(rank->out,
521
0
      VIPS_DEMAND_STYLE_FATSTRIP, in, NULL))
522
0
    return -1;
523
0
  rank->out->Xsize -= rank->width;
524
0
  rank->out->Ysize -= rank->height - 1;
525
526
0
  if (vips_image_generate(rank->out,
527
0
      vips_rank_start,
528
0
      vips_rank_generate,
529
0
      vips_rank_stop,
530
0
      in, rank))
531
0
    return -1;
532
533
0
  rank->out->Xoffset = 0;
534
0
  rank->out->Yoffset = 0;
535
536
0
  vips_reorder_margin_hint(rank->out, rank->width * rank->height);
537
538
0
  return 0;
539
0
}
540
541
static void
542
vips_rank_class_init(VipsRankClass *class)
543
1
{
544
1
  GObjectClass *gobject_class = G_OBJECT_CLASS(class);
545
1
  VipsObjectClass *object_class = (VipsObjectClass *) class;
546
547
1
  gobject_class->set_property = vips_object_set_property;
548
1
  gobject_class->get_property = vips_object_get_property;
549
550
1
  object_class->nickname = "rank";
551
1
  object_class->description = _("rank filter");
552
1
  object_class->build = vips_rank_build;
553
554
1
  VIPS_ARG_IMAGE(class, "out", 2,
555
1
    _("Output"),
556
1
    _("Output image"),
557
1
    VIPS_ARGUMENT_REQUIRED_OUTPUT,
558
1
    G_STRUCT_OFFSET(VipsRank, out));
559
560
1
  VIPS_ARG_INT(class, "width", 4,
561
1
    _("Width"),
562
1
    _("Window width in pixels"),
563
1
    VIPS_ARGUMENT_REQUIRED_INPUT,
564
1
    G_STRUCT_OFFSET(VipsRank, width),
565
1
    1, 100000, 11);
566
567
1
  VIPS_ARG_INT(class, "height", 5,
568
1
    _("Height"),
569
1
    _("Window height in pixels"),
570
1
    VIPS_ARGUMENT_REQUIRED_INPUT,
571
1
    G_STRUCT_OFFSET(VipsRank, height),
572
1
    1, 100000, 11);
573
574
1
  VIPS_ARG_INT(class, "index", 6,
575
1
    _("Index"),
576
1
    _("Select pixel at index"),
577
1
    VIPS_ARGUMENT_REQUIRED_INPUT,
578
1
    G_STRUCT_OFFSET(VipsRank, index),
579
1
    0, 100000000, 50);
580
1
}
581
582
static void
583
vips_rank_init(VipsRank *rank)
584
0
{
585
0
  rank->width = 11;
586
0
  rank->height = 11;
587
0
  rank->index = 50;
588
0
}
589
590
/**
591
 * vips_rank: (method)
592
 * @in: input image
593
 * @out: (out): output image
594
 * @width: width of region
595
 * @height: height of region
596
 * @index: select pixel
597
 * @...: `NULL`-terminated list of optional named arguments
598
 *
599
 * [method@Image.rank] does rank filtering on an image. A window of size @width by
600
 * @height is passed over the image. At each position, the pixels inside the
601
 * window are sorted into ascending order and the pixel at position @index is
602
 * output. @index numbers from 0.
603
 *
604
 * It works for any non-complex image type, with any number of bands.
605
 * The input is expanded by copying edge pixels before performing the
606
 * operation so that the output image has the same size as the input.
607
 * Edge pixels in the output image are therefore only approximate.
608
 *
609
 * For a median filter with mask size m (3 for 3x3, 5 for 5x5, etc.) use
610
 *
611
 * ```c
612
 * vips_rank(in, out, m, m, m * m / 2);
613
 * ```
614
 *
615
 * The special cases n == 0 and n == m * m - 1 are useful dilate and
616
 * expand operators.
617
 *
618
 * ::: seealso
619
 *     [method@Image.conv], [method@Image.median], [method@Image.spcor].
620
 *
621
 * Returns: 0 on success, -1 on error
622
 */
623
int
624
vips_rank(VipsImage *in, VipsImage **out,
625
  int width, int height, int index, ...)
626
0
{
627
0
  va_list ap;
628
0
  int result;
629
630
0
  va_start(ap, index);
631
0
  result = vips_call_split("rank", ap, in, out, width, height, index);
632
0
  va_end(ap);
633
634
0
  return result;
635
0
}
636
637
/**
638
 * vips_median: (method)
639
 * @in: input image
640
 * @out: (out): output image
641
 * @size: size of region
642
 * @...: `NULL`-terminated list of optional named arguments
643
 *
644
 * A convenience function equivalent to:
645
 *
646
 * ```c
647
 * vips_rank(in, out, size, size, (size * size) / 2);
648
 * ```
649
 *
650
 * ::: seealso
651
 *     [method@Image.rank].
652
 *
653
 * Returns: 0 on success, -1 on error
654
 */
655
int
656
vips_median(VipsImage *in, VipsImage **out, int size, ...)
657
0
{
658
0
  va_list ap;
659
0
  int result;
660
661
0
  va_start(ap, size);
662
0
  result = vips_call_split("rank", ap, in, out,
663
0
    size, size, (size * size) / 2);
664
0
  va_end(ap);
665
666
0
  return result;
667
0
}