數字影象處理——影象分割
阿新 • • 發佈:2018-11-21
基本全域性閾值演算法:
1.設定初始灰度值T,可設為影象的平均灰度值
2.用T把影象分成兩部分G1和G2,G1的灰度值大於T,G2的灰度值小於等於T
3.計算G1,G2的平均灰度值m1,m2
4.更新T=(m1+m2)/2
5.重複2~4直到T的變化量小於某個很小的閾值
Matlab程式碼:
clc,clear f1 = imread('blobz1.png'); f2 = imread('blobz2.png'); figure; subplot(1,2,1),imhist(f1),title('原影象(光照均勻)'); subplot(1,2,2),imhist(f2),title('原影象(光照不均勻)'); figure; subplot(1,2,1),imshow(f1),title('光照均勻'); subplot(1,2,2),imshow(f2),title('光照不均勻'); [h1,w1] = size(f1); [h2,w2] = size(f2); delta_T = 1; T_last = sum(f1(:))/(h1*w1); % 用影象的平均灰度作為初始值 T_new = 125; while abs(T_new - T_last) > delta_T g1 = f1(logical(f1>T_last)); % 找出閾值以上的畫素 c1 = sum(sum(logical(f1>T_last))); m1 = sum(sum(g1))/c1; % 計算g1的平均灰度值 g2 = f1(logical(f1<=T_last)); % 找出閾值以下的畫素 c2 = sum(sum(logical(f1<=T_last))); m2 = sum(sum(g2))/c2; T_last = T_new; T_new = (m1+m2)/2; % 更新閾值 end T_last = floor(T_last) f1(logical(f1>T_last)) = 255; % 把背景置為最亮 f1 = uint8(f1); T_last = sum(sum(f2))/(h2*w2); % 用影象的平均灰度作為初始值 T_new = 150; while abs(T_new - T_last) > delta_T g1 = f2(logical(f2>T_last)); % 找出閾值以上的畫素 c1 = sum(sum(logical(f2>T_last))); m1 = sum(sum(g1))/c1; g2 = f2(logical(f2<=T_last)); % 找出閾值以下的畫素 c2 = sum(sum(logical(f2<=T_last))); m2 = sum(sum(g2))/c2; % 計算g2的平均灰度值 T_last = T_new; T_new = (m1+m2)/2; % 更新閾值 end T_last = floor(T_last) f2(logical(f2>T_last)) = 255; % 把背景置為最亮 f2 = uint8(f2); figure; subplot(1,2,1),imshow(f1),title('光照均勻'); subplot(1,2,2),imshow(f2),title('光照不均勻');
測試影象:
執行結果: