OpenCV——双峰阈值分割

 此方法适用于图像直方图呈现双峰形状。如下图。

方法设计:结果与th敏感。若图像直方图呈现多峰,判定不理想。

#include <opencv2\opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

/***************
*img : 图像
*th  :  设置预估阈值
*itertime : 迭代次数
********************/
int PeakSplit(Mat &img, int th, int itertime)
{
	int hist[256] = {}; //直方图数据
	for (int i = 0; i < img.rows; i++)
	{
		for (int j = 0; j < img.cols; j++)
		{
			hist[img.at<uchar>(i, j)]++;
		}
	}

	int p1 = 0, p1_v = 0; //峰值坐标 和 峰值数值
	int p2 = 255, p2_v = 0;
	int pth = th;
	while (itertime--)
	{
		for (int i = p1; i <= pth; i++)
		{
			if (hist[i] > p1_v)
			{
				p1_v = hist[i];
				p1 = i;
			}

		}
		for (int i = p2; i > pth; i--)
		{
			if (hist[i] > p2_v)
			{
				p2_v = hist[i];
				p2 = i;
			}
		}
		int tmp_th = (p1 + p2) / 2; //更新阈值为两个峰值坐标中心
		if (pth == tmp_th)
			break;
		else
			pth = tmp_th;

	}
	return pth;
}

void main()
{
	Mat image = imread("1.jpg", IMREAD_GRAYSCALE);
	int otsu_th = 0;
	Mat dst;
	otsu_th = threshold(image, dst, 0, 255, THRESH_OTSU);
	cout << "otsu th >> " << otsu_th << endl;
	int peak_th = 0;
	peak_th = PeakSplit(image, 20, 10);
	cout << "peak th >> " << peak_th << endl;
	imshow("src", image);
	waitKey();


}

 

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值