Coverage Report

Created: 2026-12-01 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libvips/libvips/conversion/smartcrop.c
Line
Count
Source
1
/* crop an image down to a specified size by removing boring parts
2
 *
3
 * Adapted from sharp's smartcrop feature, with kind permission.
4
 *
5
 * 1/3/17
6
 *  - first version, from sharp
7
 * 14/3/17
8
 *  - revised attention smartcrop
9
 * 8/6/17
10
 *  - revised again
11
 * 15/9/18 lovell
12
 *  - move shrink to start of processing
13
 * 22/9/18 jcupitt
14
 *  - add low and high
15
 * 19/3/20 jcupitt
16
 *  - add all
17
 * 26/11/22 ejoebstl
18
 *  - expose location of interest when using attention based cropping
19
 */
20
21
/*
22
23
  This file is part of VIPS.
24
25
  VIPS is free software; you can redistribute it and/or modify
26
  it under the terms of the GNU Lesser General Public License as published by
27
  the Free Software Foundation; either version 2 of the License, or
28
  (at your option) any later version.
29
30
  This program is distributed in the hope that it will be useful,
31
  but WITHOUT ANY WARRANTY; without even the implied warranty of
32
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33
  GNU Lesser General Public License for more details.
34
35
  You should have received a copy of the GNU Lesser General Public License
36
  along with this program; if not, write to the Free Software
37
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
38
  02110-1301  USA
39
40
 */
41
42
/*
43
44
  These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
45
46
 */
47
48
/*
49
#define VIPS_DEBUG
50
 */
51
52
#ifdef HAVE_CONFIG_H
53
#include <config.h>
54
#endif /*HAVE_CONFIG_H*/
55
#include <glib/gi18n-lib.h>
56
57
#include <stdio.h>
58
#include <string.h>
59
#include <stdlib.h>
60
61
#include <vips/vips.h>
62
#include <vips/debug.h>
63
64
#include "pconversion.h"
65
66
#include "bandary.h"
67
68
typedef struct _VipsSmartcrop {
69
  VipsConversion parent_instance;
70
71
  VipsImage *in;
72
  int width;
73
  int height;
74
  VipsInteresting interesting;
75
  int interesting_x;
76
  int interesting_y;
77
  gboolean premultiplied;
78
79
  int attention_x;
80
  int attention_y;
81
82
} VipsSmartcrop;
83
84
typedef VipsConversionClass VipsSmartcropClass;
85
86
2
G_DEFINE_TYPE(VipsSmartcrop, vips_smartcrop, VIPS_TYPE_CONVERSION);
87
2
88
2
static int
89
2
vips_smartcrop_score(VipsSmartcrop *smartcrop, VipsImage *in,
90
2
  int left, int top, int width, int height, double *score)
91
2
{
92
0
  VipsImage **t = (VipsImage **)
93
0
    vips_object_local_array(VIPS_OBJECT(smartcrop), 2);
94
95
0
  if (vips_extract_area(in, &t[0], left, top, width, height, NULL) ||
96
0
    vips_hist_find(t[0], &t[1], NULL) ||
97
0
    vips_hist_entropy(t[1], score, NULL))
98
0
    return -1;
99
100
0
  return 0;
101
0
}
102
103
/* Entropy-style smartcrop. Repeatedly discard low interest areas. This should
104
 * be faster for very large images.
105
 */
106
static int
107
vips_smartcrop_entropy(VipsSmartcrop *smartcrop,
108
  VipsImage *in, int *left, int *top)
109
0
{
110
0
  int max_slice_size;
111
0
  int width;
112
0
  int height;
113
114
0
  *left = 0;
115
0
  *top = 0;
116
0
  width = in->Xsize;
117
0
  height = in->Ysize;
118
119
  /* How much do we trim by each iteration? Aim for 8 steps in the axis
120
   * that needs trimming most.
121
   */
122
0
  max_slice_size = VIPS_MAX(
123
0
    ceil((width - smartcrop->width) / 8.0),
124
0
    ceil((height - smartcrop->height) / 8.0));
125
126
  /* Repeatedly take a slice off width and height until we
127
   * reach the target.
128
   */
129
0
  while (width > smartcrop->width ||
130
0
    height > smartcrop->height) {
131
0
    const int slice_width =
132
0
      VIPS_MIN(width - smartcrop->width, max_slice_size);
133
0
    const int slice_height =
134
0
      VIPS_MIN(height - smartcrop->height, max_slice_size);
135
136
0
    if (slice_width > 0) {
137
0
      double left_score;
138
0
      double right_score;
139
140
0
      if (vips_smartcrop_score(smartcrop, in,
141
0
          *left, *top,
142
0
          slice_width, height, &left_score))
143
0
        return -1;
144
145
0
      if (vips_smartcrop_score(smartcrop, in,
146
0
          *left + width - slice_width, *top,
147
0
          slice_width, height, &right_score))
148
0
        return -1;
149
150
0
      width -= slice_width;
151
0
      if (left_score < right_score)
152
0
        *left += slice_width;
153
0
    }
154
155
0
    if (slice_height > 0) {
156
0
      double top_score;
157
0
      double bottom_score;
158
159
0
      if (vips_smartcrop_score(smartcrop, in,
160
0
          *left, *top,
161
0
          width, slice_height, &top_score))
162
0
        return -1;
163
164
0
      if (vips_smartcrop_score(smartcrop, in,
165
0
          *left, *top + height - slice_height,
166
0
          width, slice_height, &bottom_score))
167
0
        return -1;
168
169
0
      height -= slice_height;
170
0
      if (top_score < bottom_score)
171
0
        *top += slice_height;
172
0
    }
173
0
  }
174
175
0
  return 0;
176
0
}
177
178
/* Calculate sqrt(b1^2 + b2^2 ...)
179
 */
180
static int
181
pythagoras(VipsSmartcrop *smartcrop, VipsImage *in, VipsImage **out)
182
0
{
183
0
  VipsImage **t = (VipsImage **)
184
0
    vips_object_local_array(VIPS_OBJECT(smartcrop),
185
0
      2 * in->Bands + 1);
186
187
0
  int i;
188
189
0
  for (i = 0; i < in->Bands; i++)
190
0
    if (vips_extract_band(in, &t[i], i, NULL))
191
0
      return -1;
192
193
0
  for (i = 0; i < in->Bands; i++)
194
0
    if (vips_multiply(t[i], t[i], &t[i + in->Bands], NULL))
195
0
      return -1;
196
197
0
  if (vips_sum(&t[in->Bands], &t[2 * in->Bands], in->Bands, NULL) ||
198
0
    vips_pow_const1(t[2 * in->Bands], out, 0.5, NULL))
199
0
    return -1;
200
201
0
  return 0;
202
0
}
203
204
static int
205
vips_smartcrop_attention(VipsSmartcrop *smartcrop,
206
  VipsImage *in, int *left, int *top, int *attention_x, int *attention_y)
207
0
{
208
  /* From smartcrop.js.
209
   */
210
0
  static double skin_vector[] = { -0.78, -0.57, -0.44 };
211
0
  static double ones[] = { 1.0, 1.0, 1.0 };
212
213
0
  VipsImage **t = (VipsImage **)
214
0
    vips_object_local_array(VIPS_OBJECT(smartcrop), 24);
215
216
0
  double hscale;
217
0
  double vscale;
218
0
  double sigma;
219
0
  double max;
220
0
  int x_pos;
221
0
  int y_pos;
222
223
  /* The size we shrink to gives the precision with which we can place
224
   * the crop
225
   */
226
0
  hscale = 32.0 / in->Xsize;
227
0
  vscale = 32.0 / in->Ysize;
228
0
  sigma = hypot(smartcrop->width * hscale, smartcrop->height * vscale);
229
0
  sigma = VIPS_MAX(sigma / 10, 1.0);
230
231
0
  if (vips_resize(in, &t[17], hscale,
232
0
      "vscale", vscale,
233
0
      NULL))
234
0
    return -1;
235
236
  /* Simple edge detect.
237
   */
238
0
  if (!(t[21] = vips_image_new_matrixv(3, 3,
239
0
        0.0, -1.0, 0.0,
240
0
        -1.0, 4.0, -1.0,
241
0
        0.0, -1.0, 0.0)))
242
0
    return -1;
243
244
  /* Convert to XYZ and just use the first three bands.
245
   */
246
0
  if (vips_colourspace(t[17], &t[0], VIPS_INTERPRETATION_XYZ, NULL) ||
247
0
    vips_extract_band(t[0], &t[1], 0, "n", 3, NULL))
248
0
    return -1;
249
250
  /* Edge detect on Y.
251
   */
252
0
  if (vips_extract_band(t[1], &t[2], 1, NULL) ||
253
0
    vips_conv(t[2], &t[3], t[21],
254
0
      "precision", VIPS_PRECISION_INTEGER,
255
0
      NULL) ||
256
0
    vips_linear1(t[3], &t[4], 5.0, 0.0, NULL) ||
257
0
    vips_abs(t[4], &t[14], NULL))
258
0
    return -1;
259
260
  /* Look for skin colours. Taken from smartcrop.js.
261
   */
262
0
  if (
263
    /* Normalise to magnitude of colour in XYZ.
264
     */
265
0
    pythagoras(smartcrop, t[1], &t[5]) ||
266
0
    vips_divide(t[1], t[5], &t[6], NULL) ||
267
268
    /* Distance from skin point.
269
     */
270
0
    vips_linear(t[6], &t[7], ones, skin_vector, 3, NULL) ||
271
0
    pythagoras(smartcrop, t[7], &t[8]) ||
272
273
    /* Rescale to 100 - 0 score.
274
     */
275
0
    vips_linear1(t[8], &t[9], -100.0, 100.0, NULL) ||
276
277
    /* Ignore dark areas.
278
     */
279
0
    vips_more_const1(t[2], &t[10], 5.0, NULL) ||
280
0
    !(t[11] = vips_image_new_from_image1(t[10], 0.0)) ||
281
0
    vips_ifthenelse(t[10], t[9], t[11], &t[15], NULL))
282
0
    return -1;
283
284
  /* Look for saturated areas.
285
   */
286
0
  if (vips_colourspace(t[1], &t[12],
287
0
      VIPS_INTERPRETATION_LAB, NULL) ||
288
0
    vips_extract_band(t[12], &t[13], 1, NULL) ||
289
0
    vips_ifthenelse(t[10], t[13], t[11], &t[16], NULL))
290
0
    return -1;
291
292
  /* Sum, blur and find maxpos.
293
   *
294
   * The amount of blur is related to the size of the crop
295
   * area: how large an area we want to consider for the scoring
296
   * function.
297
   */
298
299
0
  if (vips_sum(&t[14], &t[18], 3, NULL) ||
300
0
    vips_gaussblur(t[18], &t[19], sigma, NULL) ||
301
0
    vips_max(t[19], &max, "x", &x_pos, "y", &y_pos, NULL))
302
0
    return -1;
303
304
  /* Transform back into image coordinates.
305
   */
306
0
  *attention_x = x_pos / hscale;
307
0
  *attention_y = y_pos / vscale;
308
309
  /* Centre the crop over the max.
310
   */
311
0
  *left = VIPS_CLIP(0,
312
0
    *attention_x - smartcrop->width / 2,
313
0
    in->Xsize - smartcrop->width);
314
0
  *top = VIPS_CLIP(0,
315
0
    *attention_y - smartcrop->height / 2,
316
0
    in->Ysize - smartcrop->height);
317
318
0
  return 0;
319
0
}
320
321
static int
322
vips_smartcrop_build(VipsObject *object)
323
0
{
324
0
  VipsObjectClass *class = VIPS_OBJECT_GET_CLASS(object);
325
0
  VipsConversion *conversion = VIPS_CONVERSION(object);
326
0
  VipsSmartcrop *smartcrop = (VipsSmartcrop *) object;
327
0
  VipsImage **t = (VipsImage **) vips_object_local_array(object, 2);
328
329
0
  VipsImage *in;
330
0
  int left;
331
0
  int top;
332
333
0
  int attention_x = 0;
334
0
  int attention_y = 0;
335
336
0
  if (VIPS_OBJECT_CLASS(vips_smartcrop_parent_class)->build(object))
337
0
    return -1;
338
339
0
  if (smartcrop->width > smartcrop->in->Xsize ||
340
0
    smartcrop->height > smartcrop->in->Ysize ||
341
0
    smartcrop->width <= 0 || smartcrop->height <= 0) {
342
0
    vips_error(class->nickname, "%s", _("bad extract area"));
343
0
    return -1;
344
0
  }
345
346
0
  in = smartcrop->in;
347
348
  /* If there's an alpha, we have to premultiply before searching for
349
   * content. There could be stuff in transparent areas which we don't
350
   * want to consider.
351
   */
352
0
  if (vips_image_hasalpha(in) && !smartcrop->premultiplied) {
353
0
    if (vips_premultiply(in, &t[0], NULL))
354
0
      return -1;
355
0
    in = t[0];
356
0
  }
357
358
0
  switch (smartcrop->interesting) {
359
0
  case VIPS_INTERESTING_NONE:
360
0
  case VIPS_INTERESTING_LOW:
361
0
    left = 0;
362
0
    top = 0;
363
0
    break;
364
365
0
  case VIPS_INTERESTING_CENTRE:
366
0
    left = (in->Xsize - smartcrop->width) / 2;
367
0
    top = (in->Ysize - smartcrop->height) / 2;
368
0
    break;
369
370
0
  case VIPS_INTERESTING_ENTROPY:
371
0
    if (vips_smartcrop_entropy(smartcrop, in, &left, &top))
372
0
      return -1;
373
0
    break;
374
375
0
  case VIPS_INTERESTING_ATTENTION:
376
0
    if (vips_smartcrop_attention(smartcrop, in,
377
0
        &left, &top,
378
0
        &attention_x, &attention_y))
379
0
      return -1;
380
0
    break;
381
382
0
  case VIPS_INTERESTING_SPECIFIC:
383
0
    left = VIPS_CLIP(0, smartcrop->interesting_x - smartcrop->width / 2,
384
0
      in->Xsize - smartcrop->width);
385
0
    top = VIPS_CLIP(0, smartcrop->interesting_y - smartcrop->height / 2,
386
0
      in->Ysize - smartcrop->height);
387
0
    break;
388
389
0
  case VIPS_INTERESTING_HIGH:
390
0
    left = in->Xsize - smartcrop->width;
391
0
    top = in->Ysize - smartcrop->height;
392
0
    break;
393
394
0
  case VIPS_INTERESTING_ALL:
395
0
    left = 0;
396
0
    top = 0;
397
0
    smartcrop->width = in->Xsize; // FIXME: Invalidates operation cache
398
0
    smartcrop->height = in->Ysize; // FIXME: Invalidates operation cache
399
0
    break;
400
401
0
  default:
402
0
    g_assert_not_reached();
403
404
    /* Stop a compiler warning.
405
     */
406
0
    left = 0;
407
0
    top = 0;
408
0
    break;
409
0
  }
410
411
0
  g_object_set(smartcrop,
412
0
    "attention_x", attention_x,
413
0
    "attention_y", attention_y,
414
0
    NULL);
415
416
0
  if (vips_extract_area(smartcrop->in, &t[1],
417
0
      left, top,
418
0
      smartcrop->width, smartcrop->height, NULL) ||
419
0
    vips_image_write(t[1], conversion->out))
420
0
    return -1;
421
422
0
  return 0;
423
0
}
424
425
static void
426
vips_smartcrop_class_init(VipsSmartcropClass *class)
427
1
{
428
1
  GObjectClass *gobject_class = G_OBJECT_CLASS(class);
429
1
  VipsObjectClass *vobject_class = VIPS_OBJECT_CLASS(class);
430
431
1
  VIPS_DEBUG_MSG("vips_smartcrop_class_init\n");
432
433
1
  gobject_class->set_property = vips_object_set_property;
434
1
  gobject_class->get_property = vips_object_get_property;
435
436
1
  vobject_class->nickname = "smartcrop";
437
1
  vobject_class->description = _("extract an area from an image");
438
1
  vobject_class->build = vips_smartcrop_build;
439
440
1
  VIPS_ARG_IMAGE(class, "input", 0,
441
1
    _("Input"),
442
1
    _("Input image"),
443
1
    VIPS_ARGUMENT_REQUIRED_INPUT,
444
1
    G_STRUCT_OFFSET(VipsSmartcrop, in));
445
446
1
  VIPS_ARG_INT(class, "width", 4,
447
1
    _("Width"),
448
1
    _("Width of extract area"),
449
1
    VIPS_ARGUMENT_REQUIRED_INPUT,
450
1
    G_STRUCT_OFFSET(VipsSmartcrop, width),
451
1
    1, VIPS_MAX_COORD, 1);
452
453
1
  VIPS_ARG_INT(class, "height", 5,
454
1
    _("Height"),
455
1
    _("Height of extract area"),
456
1
    VIPS_ARGUMENT_REQUIRED_INPUT,
457
1
    G_STRUCT_OFFSET(VipsSmartcrop, height),
458
1
    1, VIPS_MAX_COORD, 1);
459
460
1
  VIPS_ARG_ENUM(class, "interesting", 6,
461
1
    _("Interesting"),
462
1
    _("How to measure interestingness"),
463
1
    VIPS_ARGUMENT_OPTIONAL_INPUT,
464
1
    G_STRUCT_OFFSET(VipsSmartcrop, interesting),
465
1
    VIPS_TYPE_INTERESTING, VIPS_INTERESTING_ATTENTION);
466
467
1
  VIPS_ARG_INT(class, "interesting_x", 7,
468
1
    _("Interesting x"),
469
1
    _("Horizontal position of the specific point of interest"),
470
1
    VIPS_ARGUMENT_OPTIONAL_INPUT,
471
1
    G_STRUCT_OFFSET(VipsSmartcrop, interesting_x),
472
1
    0, VIPS_MAX_COORD, 0);
473
474
1
  VIPS_ARG_INT(class, "interesting_y", 8,
475
1
    _("Interesting y"),
476
1
    _("Vertical position of the specific point of interest"),
477
1
    VIPS_ARGUMENT_OPTIONAL_INPUT,
478
1
    G_STRUCT_OFFSET(VipsSmartcrop, interesting_y),
479
1
    0, VIPS_MAX_COORD, 0);
480
481
1
  VIPS_ARG_INT(class, "attention_x", 2,
482
1
    _("Attention x"),
483
1
    _("Horizontal position of attention centre"),
484
1
    VIPS_ARGUMENT_OPTIONAL_OUTPUT,
485
1
    G_STRUCT_OFFSET(VipsSmartcrop, attention_x),
486
1
    0, VIPS_MAX_COORD, 0);
487
488
1
  VIPS_ARG_INT(class, "attention_y", 3,
489
1
    _("Attention y"),
490
1
    _("Vertical position of attention centre"),
491
1
    VIPS_ARGUMENT_OPTIONAL_OUTPUT,
492
1
    G_STRUCT_OFFSET(VipsSmartcrop, attention_y),
493
1
    0, VIPS_MAX_COORD, 0);
494
495
1
  VIPS_ARG_BOOL(class, "premultiplied", 9,
496
1
    _("Premultiplied"),
497
1
    _("Input image already has premultiplied alpha"),
498
1
    VIPS_ARGUMENT_OPTIONAL_INPUT,
499
1
    G_STRUCT_OFFSET(VipsSmartcrop, premultiplied),
500
1
    FALSE);
501
1
}
502
503
static void
504
vips_smartcrop_init(VipsSmartcrop *smartcrop)
505
0
{
506
0
  smartcrop->interesting = VIPS_INTERESTING_ATTENTION;
507
0
  smartcrop->premultiplied = FALSE;
508
0
}
509
510
/**
511
 * vips_smartcrop: (method)
512
 * @in: input image
513
 * @out: (out): output image
514
 * @width: width of area to extract
515
 * @height: height of area to extract
516
 * @...: `NULL`-terminated list of optional named arguments
517
 *
518
 * Crop an image down to a specified width and height by removing boring parts.
519
 *
520
 * Use @interesting to pick the method vips uses to decide which bits of the
521
 * image should be kept.
522
 *
523
 * You can test xoffset / yoffset on @out to find the location of the crop
524
 * within the input image.
525
 *
526
 * ::: tip "Optional arguments"
527
 *     * @interesting: [enum@Interesting] to use to find interesting areas
528
 *       (default: [enum@Vips.Interesting.ATTENTION])
529
 *     * @interesting_x: `gint`, horizontal position of the specific point of
530
 *       interest when using [enum@Vips.Interesting.SPECIFIC])
531
 *     * @interesting_y: `gint`, vertical position of the specific point of
532
 *       interest when using [enum@Vips.Interesting.SPECIFIC])
533
 *     * @premultiplied: `gboolean`, input image already has premultiplied alpha
534
 *     * @attention_x: `gint`, output, horizontal position of attention centre when
535
 *       using attention based cropping
536
 *     * @attention_y: `gint`, output, vertical position of attention centre when
537
 *       using attention based cropping
538
 *
539
 * ::: seealso
540
 *     [method@Image.extract_area].
541
 *
542
 * Returns: 0 on success, -1 on error.
543
 */
544
int
545
vips_smartcrop(VipsImage *in, VipsImage **out, int width, int height, ...)
546
0
{
547
0
  va_list ap;
548
0
  int result;
549
550
0
  va_start(ap, height);
551
0
  result = vips_call_split("smartcrop", ap, in, out, width, height);
552
0
  va_end(ap);
553
554
0
  return result;
555
0
}