itk中的图像分割算法(四)

本文介绍了一种图像处理中的阈值分割算法——最大熵阈值分割算法,并提供了详细的实现步骤及代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文继续了解自动化阈值分割算法,最大熵阈值分割算法。个人感觉,在通常情况下,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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值