本文继续了解自动化阈值分割算法,最大熵阈值分割算法。个人感觉,在通常情况下,MaxEntropy的结果,要比 OTSU 和 Iterative 好一些。
“
最大熵原理是一种选择随机变量统计特性最符合客观情况的准则”。所谓“最符合”,就是最大概率。原理点到为止,不罗嗦,参考文献中讲的很好了。这里主要看实现。
itk中提供的类:itkMaximumEntropyThresholdImageFilter
itk::Instance <itk::MaxEntropyThresholdImageFilter<RawImType, LabImType > > Thr;
Thr->SetInput(raw);
Thr->SetOutsideValue(1);
Thr->SetInsideValue(0);
std::cout << "MaxEntropy threshold: " << (float)Thr->GetThreshold() << std::endl;
自定义实现:
float current_entropy(float hist[256], int begin, int end)
{
float total = 0; // 总概率
for(int i = begin; i < end; i++)
{
total += hist[i];//像素的概率
}
float entropy = 0; // 熵
for(int i = begin; i < end; i++)
{
float probability = hist[i];
if(probability == 0)
continue;
probability /= total;
entropy += -probability*log(probability);
}
return entropy;
}
//
int KswMaxEntropyThreshold(ImageType *src)
{
ImageType::RegionType inputRegion = src->GetLargestPossibleRegion();
ImageType::SizeType size = inputRegion.GetSize();//获得图像大小
int width = size[0];//宽
int height = size[1];//高
//histogram 获得灰度直方图
float histogram[256] = {0};
typedef itk::ImageRegionIteratorWithIndex<ImageType> FieldIterator;
FieldIterator fieldIter( src, src->GetLargestPossibleRegion());//创建一个像素迭代器
fieldIter.GoToBegin();//迭代器指向图像数组开始
ImageType2D::IndexType index;
while( !fieldIter.IsAtEnd() )//不到最后一个点,一直循环下去
{
index=fieldIter.GetIndex();//获得该点坐标
unsigned char p = src->GetPixel(index);//获得该点像素值
histogram[p]++;//放入灰度直方图
++fieldIter;
}
int threshold = 0;
float max_entropy = 0;
// 循环计算,得到做大熵以及分割阈值
for(int i = 0; i < 256; i++)
{
float entropy = current_entropy(histogram, 0, i) + current_entropy(histogram, i+1, 256);
if(entropy > max_entropy)
{
max_entropy = entropy;
threshold = i;
}
}
return threshold;
}
“悟空过来!我问你弄什么精神,变什么松树?这个功夫,可好在人前卖弄?假如你见别人有,不要求他?别人见你有,必然求你。你若畏祸却要传他,若不传他,必然加害,你之性命又不可保。”
---菩提祖师
参考文献:
1.http://blog.youkuaiyun.com/crond123/article/details/3952597
2.http://blog.youkuaiyun.com/bendanban/article/details/47058355
3.http://blog.youkuaiyun.com/xueyingxue001/article/details/50773796
4.http://blog.youkuaiyun.com/xueyingxue001/article/details/51940541