Pengolahan Piksel: Image Negative, Gamma Correction, dan Contrast Stretching

Dokumentasi implementasi pengolahan piksel (step-by-step) menggunakan MATLAB.

1. Kode MATLAB

% =========================================================================
% SOAL 1: PENGOLAHAN PIKSEL (PIXEL PROCESSING)
% - Image Negative
% - Gamma Correction (gamma = 2, c = 1) + Normalisasi
% - Contrast Stretching (E = 2) + Normalisasi
% =========================================================================

% 1. Baca Citra
img = imread('cameraman.tif');
if size(img, 3) == 3
    img = rgb2gray(img);
end
img_double = double(img);

% -------------------------------------------------------------------------
% A. IMAGE NEGATIVE
% Rumus: s = (L - 1) - r  (untuk 8-bit: 255 - r)
% -------------------------------------------------------------------------
img_negative = 255 - img_double;
img_negative = uint8(img_negative);

% -------------------------------------------------------------------------
% B. GAMMA CORRECTION
% Rumus: s = c * (r ^ gamma)
% Parameter: gamma = 2, c = 1
% -------------------------------------------------------------------------
% Normalisasi input r ke rentang [0, 1]
r_norm = img_double / 255; 
gamma_val = 2;
c_val = 1;

% Transformasi Power-Law (Gamma)
s_gamma = c_val * (r_norm .^ gamma_val); 

% Normalisasi kembali hasil ke rentang [0, 255]
s_gamma_norm = (s_gamma - min(s_gamma(:))) / (max(s_gamma(:)) - min(s_gamma(:)));
img_gamma = uint8(s_gamma_norm * 255);

% -------------------------------------------------------------------------
% C. CONTRAST STRETCHING
% Rumus: s = 1 / (1 + (m / r)^E)
% Parameter: E = 2, m = rata-rata intensitas citra (normalisasi)
% -------------------------------------------------------------------------
r_norm = img_double / 255;
m_val = mean(r_norm(:)); % Nilai rata-rata piksel
E_val = 2;
eps_val = 1e-5;          % Menghindari pembagian dengan nol

% Transformasi Sigmoid/Contrast Stretching
s_stretch = 1 ./ (1 + (m_val ./ (r_norm + eps_val)) .^ E_val);

% Normalisasi hasil ke rentang [0, 255]
s_stretch_norm = (s_stretch - min(s_stretch(:))) / (max(s_stretch(:)) - min(s_stretch(:)));
img_contrast = uint8(s_stretch_norm * 255);

% -------------------------------------------------------------------------
% VISUALISASI HASIL
% -------------------------------------------------------------------------
figure;
subplot(2,2,1); imshow(img); title('Citra Asli');
subplot(2,2,2); imshow(img_negative); title('Image Negative');
subplot(2,2,3); imshow(img_gamma); title('Gamma Correction (\gamma=2, c=1)');
subplot(2,2,4); imshow(img_contrast); title('Contrast Stretching (E=2)');