Matlab影像處理(一)直方圖
%% 直方圖
close all; clear; clc;
fprintf('影像直方圖\n\n')
img=imread('Color_lena512.bmp');
Graybar = zeros(1, 256);
Rbar = zeros(1, 256);
Gbar = zeros(1, 256);
Bbar = zeros(1, 256);
[row, col] = size(img(:, :, 1));
grayimg = rgb2gray(uint8(img));
for i=1:row
for j=1:col
A = grayimg(i ,j) + 1;
Graybar(1, A) = Graybar(1, A) + 1;
R = img(i, j, 1) + 1;
Rbar(1, R) = Rbar(1, R) + 1;
G = img(i, j, 2) + 1;
Gbar(1, G) = Gbar(1, G) + 1;
B = img(i, j, 3) + 1;
Bbar(1, B) = Rbar(1, B) + 1;
end
end
subplot(2, 2, 1), bar(Graybar, 'k'), title('灰階直方圖')
subplot(2, 2, 2), bar(Rbar, 'r'), title('R直方圖')
subplot(2, 2, 3), bar(Gbar, 'g'), title('G直方圖')
subplot(2, 2, 4), bar(Bbar, 'b'), title('B直方圖')
%% 等化法
close all; clear; clc;
img = imread('Color_lena512.bmp');
Grayimg = rgb2gray(img);
[row, col] = size(img(:, :, 1));
outputimg = zeros(row, col);
outputbar = zeros(1, 256);
Graybar = zeros(1, 256);
cdf = zeros(1, 256);
for i=1:row
for j=1:col
A = Grayimg(i, j);
Graybar(1, A) = Graybar(1, A) + 1;
end
end
subplot(2, 2, 1), imshow(Grayimg), title('灰階原圖')
subplot(2, 2, 2), bar(Graybar), title('原直方圖')
count = 0;
for i=1:256
for j=1:i
cdf(1, i) = cdf(1, i) + Graybar(1, j);
end
end
pcdf = sort(cdf);
for i=1:256
if pcdf(1, i)>0
cdfmin = pcdf(1, i);
break
end
end
L = 2.^8;
h =@(v) round( ((cdf(1, v) - cdfmin)./((row.*col) - cdfmin)).*(L - 1) )
for i=1:row
for j=1:col
outputimg(i, j) = h(img(i, j) + 1);
A = outputimg(i, j) + 1;
outputbar(1, A) = outputbar(1, A) + 1;
end
end
subplot(2, 2, 3), imshow(uint8(outputimg)), title('灰階等化後圖')
subplot(2, 2, 4), bar(outputbar), title('等化後直方圖')
留言
張貼留言