Pengolahan Mask (Smoothing Filter): Box Filter dan Median Filter 3x3

Dokumentasi pemfilteran spasial halus (smoothing/low-pass filter) menggunakan Box Filter dan Median Filter ukuran 3x3.

1. Kode MATLAB

% =========================================================================
% SOAL 3: PENGOLAHAN MASK - SMOOTHING FILTER
% a. Box Filter Ukuran 3x3
% b. Median Filter Ukuran 3x3
% =========================================================================

img = imread('cameraman.tif');
if size(img, 3) == 3
    img = rgb2gray(img);
end
[rows, cols] = size(img);
img_double = double(img);

% Zero/Replicate Padding untuk penanganan batas tepi
img_padded = padarray(img_double, [1 1], 'replicate');

% -------------------------------------------------------------------------
% A. BOX FILTER 3x3 (Averaging / Linear Smoothing Filter)
% Kernel: 1/9 * ones(3,3)
% -------------------------------------------------------------------------
img_box = zeros(rows, cols);
box_kernel = ones(3, 3) / 9;

for i = 2:rows+1
    for j = 2:cols+1
        % Ambil blok 3x3
        sub_img = img_padded(i-1:i+1, j-1:j+1);
        
        % Konvolusi lokal (penjumlahan hasil kali elemen)
        img_box(i-1, j-1) = sum(sum(sub_img .* box_kernel));
    end
end
img_box = uint8(img_box);

% -------------------------------------------------------------------------
% B. MEDIAN FILTER 3x3 (Non-linear Smoothing Filter)
% -------------------------------------------------------------------------
img_median = zeros(rows, cols);

for i = 2:rows+1
    for j = 2:cols+1
        % Ambil blok 3x3
        sub_img = img_padded(i-1:i+1, j-1:j+1);
        
        % Vektorkan matriks 3x3 menjadi 1D (9 elemen)
        vec_pixels = sub_img(:);
        
        % Urutkan piksel dan ambil nilai tengah (indeks ke-5)
        sorted_pixels = sort(vec_pixels);
        img_median(i-1, j-1) = sorted_pixels(5);
    end
end
img_median = uint8(img_median);

% -------------------------------------------------------------------------
% VISUALISASI HASIL
% -------------------------------------------------------------------------
figure;
subplot(1,3,1); imshow(img); title('Citra Asli');
subplot(1,3,2); imshow(img_box); title('Box Filter (3x3)');
subplot(1,3,3); imshow(img_median); title('Median Filter (3x3)');