Ansel 0.0
A darktable fork - bloat + design vision
Loading...
Searching...
No Matches
fast_guided_filter.h
Go to the documentation of this file.
1/*
2 This file is part of darktable,
3 Copyright (C) 2019-2020, 2025-2026 Aurélien PIERRE.
4 Copyright (C) 2019-2021 Pascal Obry.
5 Copyright (C) 2020-2021 Ralf Brown.
6 Copyright (C) 2020 rawfiner.
7 Copyright (C) 2020 Roman Lebedev.
8 Copyright (C) 2022 Martin Bařinka.
9 Copyright (C) 2022 Sakari Kapanen.
10 Copyright (C) 2023 Luca Zulberti.
11
12 darktable is free software: you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation, either version 3 of the License, or
15 (at your option) any later version.
16
17 darktable is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with darktable. If not, see <http://www.gnu.org/licenses/>.
24*/
25
26#pragma once
27
28#include <assert.h>
29#include <math.h>
30#include <stdlib.h>
31#include <stdio.h>
32#include <string.h>
33#include <time.h>
34
35#include "common/box_filters.h"
36#include "common/darktable.h"
37#include "common/imagebuf.h"
38#include "control/control.h"
39
40#define MIN_FLOAT exp2f(-16.0f)
41
42
48
49
50/***
51 * DOCUMENTATION
52 *
53 * Fast Iterative Guided filter for surface blur
54 *
55 * This is a fast vectorized implementation of guided filter for grey images optimized for
56 * the special case where the guiding and the guided image are the same, which is useful
57 * for edge-aware surface blur.
58 *
59 * Since the guided filter is a linear application, we can safely downscale
60 * the guiding and the guided image by a factor of 4, using a bilinear interpolation,
61 * compute the guidance at this scale, then upscale back to the original size
62 * and get a free 10x speed-up.
63 *
64 * Then, the vectorization adds another substantial speed-up. Overall, it brings a x50 to x200
65 * speed-up compared to the guided_filter.h lib. Of course, it requires every buffer to be
66 * 64-bits aligned.
67 *
68 * On top of the default guided filter, several pre- and post-processing options are provided :
69 *
70 * - mask quantization : perform a posterization of the guiding image in log2 space to
71 * help the guiding to produce smoother areas,
72 *
73 * - blending : perform a regular (linear) blending of a and b parameters after the
74 * variance analysis (aka the by-the-book guided filter), or a geometric mean of the filter output (by-the-book)
75 * and the original image, which produces a pleasing trade-off.
76 *
77 * - iterations : apply the guided filtering recursively, with kernel size increasing by sqrt(2)
78 * between each iteration, to diffuse the filter and soften edges transitions.
79 *
80 * Reference :
81 * Kaiming He, Jian Sun, Microsoft : https://arxiv.org/abs/1505.00996
82 **/
83
84
86static inline float fast_clamp(const float value, const float bottom, const float top)
87{
88 // vectorizable clamping between bottom and top values
89 return fmaxf(fminf(value, top), bottom);
90}
91
92
94static inline void interpolate_bilinear(const float *const restrict in, const size_t width_in, const size_t height_in,
95 float *const restrict out, const size_t width_out, const size_t height_out,
96 const size_t ch)
97{
98 // Fast vectorized bilinear interpolation on ch channels
99 __OMP_PARALLEL_FOR__(collapse(2))
100 for(size_t i = 0; i < height_out; i++)
101 {
102 for(size_t j = 0; j < width_out; j++)
103 {
104 // Relative coordinates of the pixel in output space
105 const float x_out = (float)j /(float)width_out;
106 const float y_out = (float)i /(float)height_out;
107
108 // Corresponding absolute coordinates of the pixel in input space
109 const float x_in = x_out * (float)width_in;
110 const float y_in = y_out * (float)height_in;
111
112 // Nearest neighbours coordinates in input space
113 size_t x_prev = (size_t)floorf(x_in);
114 size_t x_next = x_prev + 1;
115 size_t y_prev = (size_t)floorf(y_in);
116 size_t y_next = y_prev + 1;
117
118 x_prev = (x_prev < width_in) ? x_prev : width_in - 1;
119 x_next = (x_next < width_in) ? x_next : width_in - 1;
120 y_prev = (y_prev < height_in) ? y_prev : height_in - 1;
121 y_next = (y_next < height_in) ? y_next : height_in - 1;
122
123 // Nearest pixels in input array (nodes in grid)
124 const size_t Y_prev = y_prev * width_in;
125 const size_t Y_next = y_next * width_in;
126 const float *const Q_NW = (float *)in + (Y_prev + x_prev) * ch;
127 const float *const Q_NE = (float *)in + (Y_prev + x_next) * ch;
128 const float *const Q_SE = (float *)in + (Y_next + x_next) * ch;
129 const float *const Q_SW = (float *)in + (Y_next + x_prev) * ch;
130
131 // Spatial differences between nodes
132 const float Dy_next = (float)y_next - y_in;
133 const float Dy_prev = 1.f - Dy_next; // because next - prev = 1
134 const float Dx_next = (float)x_next - x_in;
135 const float Dx_prev = 1.f - Dx_next; // because next - prev = 1
136
137 // Interpolate over ch layers
138 float *const pixel_out = (float *)out + (i * width_out + j) * ch;
139
140// //LLVM warns it can't unroll -- presumably because 'ch' is not a constant
141 for(size_t c = 0; c < ch; c++)
142 {
143 pixel_out[c] = Dy_prev * (Q_SW[c] * Dx_next + Q_SE[c] * Dx_prev) +
144 Dy_next * (Q_NW[c] * Dx_next + Q_NE[c] * Dx_prev);
145 }
146 }
147 }
148
149}
150
151
153static inline int variance_analyse(const float *const restrict guide, // I
154 const float *const restrict mask, //p
155 float *const restrict ab,
156 const size_t width, const size_t height,
157 const int radius, const float feathering)
158{
159 // Compute a box average (filter) on a grey image over a window of size 2*radius + 1
160 // then get the variance of the guide and covariance with its mask
161 // output a and b, the linear blending params
162 // p, the mask is the quantised guide I
163
164 const size_t Ndim = width * height;
165 const size_t Ndimch = Ndim * 4;
166
167 /*
168 * input is array of struct : { { guide , mask, guide * guide, guide * mask } }
169 */
170 float *const restrict input = dt_pixelpipe_cache_alloc_align_float_cache(Ndimch, 0);
171 if(IS_NULL_PTR(input)) return 1;
172
173 // Pre-multiply guide and mask and pack all inputs into an array of 4x1 SIMD struct
175 for(size_t k = 0; k < Ndim; k++)
176 {
177 const size_t index = k * 4;
178 input[index] = guide[k];
179 input[index + 1] = mask[k];
180 input[index + 2] = guide[k] * guide[k];
181 input[index + 3] = guide[k] * mask[k];
182 }
183
184 // blur the guide and mask as a four-channel image to exploit data locality and SIMD
185 if(dt_box_mean(input, height, width, 4, radius, 1) != 0)
186 {
188 return 1;
189 }
190
191 // blend the result and store in output buffer
193 for(size_t idx = 0; idx < width*height; idx++)
194 {
195 const float d = fmaxf((input[4*idx+2] - input[4*idx+0] * input[4*idx+0]) + feathering, 1e-15f); // avoid division by 0.
196 const float a = (input[4*idx+3] - input[4*idx+0] * input[4*idx+1]) / d;
197 const float b = input[4*idx+1] - a * input[4*idx+0];
198 ab[2*idx] = a;
199 ab[2*idx+1] = b;
200 }
201
203 return 0;
204}
205
206
208static inline void apply_linear_blending(float *const restrict image,
209 const float *const restrict ab,
210 const size_t num_elem)
211{
212 __OMP_PARALLEL_FOR_SIMD__(aligned(image, ab:64))
213 for(size_t k = 0; k < num_elem; k++)
214 {
215 // Note : image[k] is positive at the outside of the luminance mask
216 image[k] = fmaxf(image[k] * ab[k * 2] + ab[k * 2 + 1], MIN_FLOAT);
217 }
218}
219
220
222static inline void apply_linear_blending_w_geomean(float *const restrict image,
223 const float *const restrict ab,
224 const size_t num_elem)
225{
226 __OMP_PARALLEL_FOR_SIMD__(aligned(image, ab:64))
227 for(size_t k = 0; k < num_elem; k++)
228 {
229 // Note : image[k] is positive at the outside of the luminance mask
230 image[k] = sqrtf(image[k] * fmaxf(image[k] * ab[k * 2] + ab[k * 2 + 1], MIN_FLOAT));
231 }
232}
233
234
236static inline void quantize(const float *const restrict image,
237 float *const restrict out,
238 const size_t num_elem,
239 const float sampling, const float clip_min, const float clip_max)
240{
241 // Quantize in exposure levels evenly spaced in log by sampling
242
243 if(sampling == 0.0f)
244 {
245 // No-op
246 dt_iop_image_copy(out, image, num_elem);
247 }
248 else if(sampling == 1.0f)
249 {
250 // fast track
251 __OMP_PARALLEL_FOR_SIMD__(aligned(image, out:64))
252 for(size_t k = 0; k < num_elem; k++)
253 out[k] = fast_clamp(exp2f(floorf(log2f(image[k]))), clip_min, clip_max);
254 }
255
256 else
257 {
258 // slow track
259 __OMP_PARALLEL_FOR_SIMD__(aligned(image, out:64))
260 for(size_t k = 0; k < num_elem; k++)
261 out[k] = fast_clamp(exp2f(floorf(log2f(image[k]) / sampling) * sampling), clip_min, clip_max);
262 }
263}
264
265
267static inline int fast_surface_blur(float *const restrict image,
268 const size_t width, const size_t height,
269 const int radius, float feathering, const int iterations,
270 const dt_iop_guided_filter_blending_t filter, const float scale,
271 const float quantization, const float quantize_min, const float quantize_max)
272{
273 // Works in-place on a grey image
274
275 // A down-scaling of 4 seems empirically safe and consistent no matter the image zoom level
276 // see reference paper above for proof.
277 const float scaling = 4.0f;
278 const int ds_radius = (radius < 4) ? 1 : radius / scaling;
279
280 const size_t ds_height = height / scaling;
281 const size_t ds_width = width / scaling;
282
283 const size_t num_elem_ds = ds_width * ds_height;
284 const size_t num_elem = width * height;
285
286 float *const restrict ds_image = dt_pixelpipe_cache_alloc_align_float_cache(dt_round_size_sse(num_elem_ds), 0);
287 float *const restrict ds_mask = dt_pixelpipe_cache_alloc_align_float_cache(dt_round_size_sse(num_elem_ds), 0);
288 float *const restrict ds_ab = dt_pixelpipe_cache_alloc_align_float_cache(dt_round_size_sse(num_elem_ds * 2), 0);
289 float *const restrict ab = dt_pixelpipe_cache_alloc_align_float_cache(dt_round_size_sse(num_elem * 2), 0);
290
291 if(IS_NULL_PTR(ds_image) || IS_NULL_PTR(ds_mask) || IS_NULL_PTR(ds_ab) || IS_NULL_PTR(ab))
292 {
293 dt_control_log(_("fast guided filter failed to allocate memory, check your RAM settings"));
298 return 1;
299 }
300
301 // Downsample the image for speed-up
302 interpolate_bilinear(image, width, height, ds_image, ds_width, ds_height, 1);
303
304 // Iterations of filter models the diffusion, sort of
305 for(int i = 0; i < iterations; ++i)
306 {
307 // (Re)build the mask from the quantized image to help guiding
308 quantize(ds_image, ds_mask, ds_width * ds_height, quantization, quantize_min, quantize_max);
309
310 // Perform the patch-wise variance analyse to get
311 // the a and b parameters for the linear blending s.t. mask = a * I + b
312 if(variance_analyse(ds_mask, ds_image, ds_ab, ds_width, ds_height, ds_radius, feathering) != 0)
313 {
318 return 1;
319 }
320
321 // Compute the patch-wise average of parameters a and b
322 if(dt_box_mean(ds_ab, ds_height, ds_width, 2, ds_radius, 1) != 0)
323 {
328 return 1;
329 }
330
331 if(i != iterations - 1)
332 {
333 // Process the intermediate filtered image
334 apply_linear_blending(ds_image, ds_ab, num_elem_ds);
335 }
336 }
337
338 // Upsample the blending parameters a and b
339 interpolate_bilinear(ds_ab, ds_width, ds_height, ab, width, height, 2);
340
341 // Finally, blend the guided image
342 if(filter == DT_GF_BLENDING_LINEAR)
343 apply_linear_blending(image, ab, num_elem);
344 else if(filter == DT_GF_BLENDING_GEOMEAN)
345 apply_linear_blending_w_geomean(image, ab, num_elem);
346
351 return 0;
352}
353
354// clang-format off
355// modelines: These editor modelines have been set for all relevant files by tools/update_modelines.py
356// vim: shiftwidth=2 expandtab tabstop=2 cindent
357// kate: tab-indents: off; indent-width 2; replace-tabs on; indent-mode cstyle; remove-trailing-spaces modified;
358// clang-format on
int width
Definition bilateral.h:1
int height
Definition bilateral.h:1
int dt_box_mean(float *const buf, const size_t height, const size_t width, const int ch, const int radius, const unsigned iterations)
Definition box_filters.c:1047
static const float scaling
Definition chromatic_adaptation.h:293
const float i
Definition colorspaces_inline_conversions.h:440
const float d
Definition colorspaces_inline_conversions.h:680
const dt_colormatrix_t dt_aligned_pixel_t out
Definition colorspaces_inline_conversions.h:42
const float top
Definition colorspaces_inline_conversions.h:443
void dt_control_log(const char *msg,...)
Definition control.c:530
#define dt_pixelpipe_cache_alloc_align_float_cache(pixels, id)
Definition darktable.h:447
static size_t dt_round_size_sse(const size_t size)
Definition darktable.h:403
#define __OMP_DECLARE_SIMD__(...)
Definition darktable.h:263
#define dt_pixelpipe_cache_free_align(mem)
Definition darktable.h:453
#define __DT_CLONE_TARGETS__
Definition darktable.h:367
#define __OMP_PARALLEL_FOR__(...)
Definition darktable.h:258
static const dt_aligned_pixel_simd_t value
Definition darktable.h:577
#define __OMP_PARALLEL_FOR_SIMD__(...)
Definition darktable.h:259
#define IS_NULL_PTR(p)
C is way too permissive with !=, == and if(var) checks, which can mean too many things depending on w...
Definition darktable.h:281
static __DT_CLONE_TARGETS__ int variance_analyse(const float *const restrict guide, const float *const restrict mask, float *const restrict ab, const size_t width, const size_t height, const int radius, const float feathering)
Definition fast_guided_filter.h:153
static __DT_CLONE_TARGETS__ int fast_surface_blur(float *const restrict image, const size_t width, const size_t height, const int radius, float feathering, const int iterations, const dt_iop_guided_filter_blending_t filter, const float scale, const float quantization, const float quantize_min, const float quantize_max)
Definition fast_guided_filter.h:267
dt_iop_guided_filter_blending_t
Definition fast_guided_filter.h:44
@ DT_GF_BLENDING_LINEAR
Definition fast_guided_filter.h:45
@ DT_GF_BLENDING_GEOMEAN
Definition fast_guided_filter.h:46
static __DT_CLONE_TARGETS__ void quantize(const float *const restrict image, float *const restrict out, const size_t num_elem, const float sampling, const float clip_min, const float clip_max)
Definition fast_guided_filter.h:236
#define MIN_FLOAT
Definition fast_guided_filter.h:40
static __DT_CLONE_TARGETS__ void apply_linear_blending_w_geomean(float *const restrict image, const float *const restrict ab, const size_t num_elem)
Definition fast_guided_filter.h:222
static __DT_CLONE_TARGETS__ void apply_linear_blending(float *const restrict image, const float *const restrict ab, const size_t num_elem)
Definition fast_guided_filter.h:208
static float fast_clamp(const float value, const float bottom, const float top)
Definition fast_guided_filter.h:86
static __DT_CLONE_TARGETS__ void interpolate_bilinear(const float *const restrict in, const size_t width_in, const size_t height_in, float *const restrict out, const size_t width_out, const size_t height_out, const size_t ch)
Definition fast_guided_filter.h:94
__DT_CLONE_TARGETS__ void dt_iop_image_copy(float *const __restrict__ out, const float *const __restrict__ in, const size_t nfloats)
Definition imagebuf.c:138
float *const restrict const size_t k
Definition luminance_mask.h:78
float *const restrict const size_t const size_t ch
Definition luminance_mask.h:78