procedure TForm1.OtsuAlgorithmClick(Sender: TObject;BitMap:TBitmap); //大津法求最佳阀值
var
row, col:integer;
i, T:integer;
n,P, Sum_Pi,Sum_Pi_i: array[0..256] of double;
W1, W2, U1, U2, sumpixelouble;
Sigma_1_square, Sigma_2_square, Sigma_w_square:double;
MinVariance :double;
ptrbytearray;
T_optimal:integer;
begin
MinVariance := 1.7e+308 ;
// 计算影像的总像素數
sumpixel := BitMap.Width * BitMap.Height;
// 统计影像中灰度值為i的像素數
for i := 0 to 256 do
n := 0;
for row := 0 to BitMap.Height-1 do
begin
ptr := BitMap.ScanLine[row];
for col := 0 to Bitmap.Width-1 do
n[ ptr[col] ]:=n[ ptr[col] ]+1;
end;
// 计算图像中灰度值为i的像素所出現的概率
for i := 0 to 255 do
P := n /sumpixel;
// 分別計算阀值为T时,Sum_Pi和Sum_Pi_i
Sum_Pi[0] := P[0];
Sum_Pi_i[0] := 0;
for i := 1 to 255 do
begin
Sum_Pi := Sum_Pi[i-1] + P;
Sum_Pi_i := Sum_Pi_i[i-1] + P * i;
end ; // 检查所有的灰度值,使C1和C2的变异数和为最小时
// 即为所求的最佳阀值
for T := 1 to 254 do
begin
W1:= Sum_Pi[T];
// 加上最小值检查,避免除数为零
if (Abs(W1) < 1e-9) then
W1:= 1e-9;
W2 := 1 - W1;
// 加上最小值检查,避免除数为零
if (Abs(W2) < 1e-9) then W2 := 1e-9;
U1:= Sum_Pi_i[T] / W1;
U2 := (Sum_Pi_i[255] - Sum_Pi_i[T]) / W2;
Sigma_1_square:= 0;
for i:= 0 to T do
Sigma_1_square :=Sigma_1_square+(i - U1) * ( i - U1) * P;
Sigma_1_square := Sigma_1_square / W1;
Sigma_2_square := 0;
for i := T+1 to 255 do
begin
Sigma_2_square:= Sigma_2_square+(i- U2) * (i - U2) * P;
end ;
Sigma_2_square := Sigma_2_square / W2;
Sigma_w_square := W1 * Sigma_1_square + W2 * Sigma_2_square;
if(Sigma_w_square < MinVariance) then
begin
MinVariance := Sigma_w_square;
optialT:=T;
end;
end;
// 回传最佳阀值
bestGrayLabel.Caption:=inttostr(optialT);
end;
是不是这个?