1、原理参考:https://www.cnblogs.com/guopengfei/p/4759569.html
2、公式推导:
3、同halcon的binary_threshold (Image, Region, \'max_separability\', \'light\', UsedThreshold3)算子。
具体实现如下:
gray_histo (Region, Image, AbsoluteHisto, RelativeHisto) get_image_size (Image, Width, Height) TotalSize:=Width*Height intensity (Region, Image, avgValue, Deviation)//avgValue图像总平均灰度 MaxDiff:=0.0 Diff:=0.0 //方差 Thre:=0 delta_max:=0 for i := 0 to 255 by 1 w0:=0.0 u0:=0.0 w1:=0.0 u1:=0.0 uo_temp:=0 u1_temp:=0 delta_temp:=0 **背景部分 for j:=0 to i by 1 w0:=w0+AbsoluteHisto[j] uo_temp:=uo_temp+j*AbsoluteHisto[j] endfor **前景部分 w1:=TotalSize-w0 u1_temp:=avgValue*TotalSize-uo_temp **计算两类的平均灰度 if(w0==0 or w1==0) u0:=0 u1:=0 else u0:=uo_temp/w0 u1:=u1_temp/w1 endif **依次找到最大类间方差下的阈值 delta_temp:=w0*w1*pow((u0-u1),2) if(delta_temp>delta_max) delta_max := delta_temp Thre:=i endif endfor return ()
优化后的代码实现如下:
gray_histo (Region, Image, AbsoluteHisto, RelativeHisto) intensity (Region, Image, avgValue, Deviation)//avgValue图像总平均灰度 wk:=0.0 //分开后前景像素点数占图像的比例 uk:=0.0 //分开后前景像素数的平均灰度值 MaxDiff:=0.0 Diff:=0.0 //方差 Thre:=0 for Index := 0 to 255 by 1 wk:=wk+RelativeHisto[Index] uk:=uk+RelativeHisto[Index]*Index if(wk<=0.0 or wk>=1.0) Diff:=0 else Diff:=(avgValue*wk-uk)*(avgValue*wk-uk )/(wk*(1-wk)) endif if(Diff>MaxDiff) MaxDiff:=Diff Thre:=Index endif endfor return ()