最大熵阈值分割实现

该博客介绍了最大熵值法在图像分割中的应用,提供了一段C++代码实现。通过对输入图像的像素值进行统计,计算不同阈值下的前后区域熵,选择熵最大的阈值进行分割,最终将图像二值化。

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

原理:
在这里插入图片描述
实现:

/**
 * @description:	最大熵值法图像分割
 * @param src		输入图像
 * @param dst		输出图像
 */
void maxentropy(cv::Mat& src, cv::Mat& dst)
{
	int thresh = 0;
	int histogram[256] = { 0 };
	for (int i = 0; i < src.rows; ++i)
	{
		const uchar* ptr = src.ptr<uchar>(i);
		for (int j = 0; j < src.cols; ++j)
		{
			if (ptr[j] == 0) continue;
			histogram[ptr[j]]++;
		}
	}

	float p = 0.0; 
	float max_entropy = 0.0; 
	int totalnum = src.rows*src.cols;
	for (int i = 0; i < 256; ++i)
	{
		float front_entropy = 0.0; 
		float back_entropy = 0.0; 

		int frontnum = 0;
		for (int j = 0; j < i; ++j) 
		{
			frontnum += histogram[j];
		}
		for (int j = 0; j < i; ++j)
		{
			if (histogram[j] != 0)
			{
				p = (float)histogram[j] / frontnum;
				front_entropy += p*log(1 / p);
			}
		}

		for (int k = i; k < 256; ++k) 
		{
			if (histogram[k] != 0)
			{
				p = (float)histogram[k] / (totalnum - frontnum);
				back_entropy += p*log(1 / p);
			}
		}

		if (front_entropy + back_entropy > max_entropy) 
		{
			max_entropy = front_entropy + back_entropy;
			thresh = i ;
		}
	}

	dst = src.clone();
	for (int i = 0; i < dst.rows; ++i)
	{
		uchar* ptr = dst.ptr<uchar>(i);
		for (int j = 0; j < dst.cols; ++j)
		{
			if (ptr[j] > thresh)
				ptr[j] = 255;
			else
				ptr[j] = 0;
		}
	}
}

代码传送门:https://github.com/taifyang/OpenCV-algorithm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

给算法爸爸上香

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值