Bilateral filter templates are mainly generated using two templates. The first is a Gaussian template, and the second is a template generated using the gray-level difference value as the function coefficient. Then the two templates get the final bilateral filter template by dot multiplication.
The first template is a global template, so you only need to generate it once. The second template needs to calculate each pixel once, so it needs to be placed in the loop to generate it, which is like surface blur. Well, surface blur uses a truncation filter.
I have referred to the formula here, but the second Gaussian filter she gave does not seem to be a mean filter, but a gray difference as the independent variable. Here are some theories and implementations of the truncation mean filter,
The Code is as follows:
Clear all; close all1_clc1_img1_imread('lena.jpg '); IMG = mat2gray (IMG); [m n] = size (IMG); imshow (IMG); r = 10; % template radius imgn = zeros (m + 2 * r + 1, n + 2 * r + 1); imgn (R + 1: m + R, R + 1: N + R) = IMG; imgn (1: R, R + 1: N + R) = IMG (1: R, 1: N); % extended upper boundary imgn (1: m + R, N + R + 1: n + 2 * r + 1) = imgn (1: m + R, N: N + r ); % extend the right boundary imgn (m + R + 1: m + 2 * r + 1, R + 1: n + 2 * r + 1) = imgn (M: m + R, R + 1: n + 2 * r + 1); % extended lower boundary imgn (1: m + 2 * r +: R) = imgn (1: m + 2 * r + 1, R + * r); % extends the left boundary sigma_d = 2; sigma_r = 0.1; [x, y] = meshgrid (-R: R, -R: R); W1 = exp (-(X. ^ 2 + Y. ^ 2)/(2 * sigma_d ^ 2); % Take the distance as the independent Gaussian filter H = waitbar (0, 'Wait... '); for I = R + 1: m + R for J = R + 1: N + R W2 = exp (-(imgn (I-r: I + R, j-R: J + r)-imgn (I, j )). ^ 2/(2 * sigma_r ^ 2); % Gaussian filter W = W1. * W2; S = imgn (I-r: I + R, J-R: J + r ). * w; imgn (I, j) = sum (s)/sum (w); End waitbar (I/M); endclose (h) figure; imshow (mat2gray (imgn (R + 1: m + R, R + 1: N + r )));
Effect:
Source image
After bilateral Filtering