摘要:本文主要向大家介绍了 C/C++知识点之opencv中自适应阈值函数的实现(c++),通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
本文主要向大家介绍了 C/C++知识点之opencv中自适应阈值函数的实现(c++),通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
原理:
1 //计算灰度最大最小值
2 void MaxGrayValue(Mat image,int &max,int &min)
3 {
4 max = 0;
5 min = 255;
6 Mat *im = reinterpret_cast
7 int height = image.rows;
8 int width = image.cols;
9 int N = height * width;
10 //cout << "125" << " " << "125" << " " << static_cast
11 for (int i = 0; i < height; i++)
12 {
13 for (int j = 0; j < width; j++)
14 {
15 if ((static_cast
16 max = static_cast
17 else if ((static_cast
18 min = static_cast
19 }
20 }
21 }
1 //自适应阈值 注:传入的只能是灰度图像
2 void adapthreshold(Mat &image)
3 {
4 int max, min; //保存最大和最小灰度值
5 MaxGrayValue(image, max, min); //计算出最大最小灰度值
6 int grayvalue; //用于暂时存取每个点的灰度值
7 int Threshold = (max + min)/2; //初始阈值
8 int Temp_Threshold = Threshold; //用于存取每次迭代后的阈值
9 int big_than_th; //用于累加大于阈值的灰度值
10 int bigcount; //用于存放大于阈值灰度值的像素点数量
11 int sma_than_th; //用于累加小于阈值的灰度值
12 int smacount; //用于存放小于阈值灰度值的像素点数量
13 Mat *im = reinterpret_cast
14 //Mat *im = ℑ
15 int height = image.rows; //获取图像高度
16 int width = image.cols; //获取图像宽度
17
18
19 for (int k = 0; k < 50; k++) //计算阈值,最大迭代50次
20 {
21 big_than_th = 0;
22 bigcount = 0;
23 sma_than_th = 0;
24 smacount = 0;
25 for (int i = 0; i < height; i++)
26 {
27 for (int j = 0; j < width; j++)
28 {
29 grayvalue = static_cast
30 if (grayvalue>Threshold) //如果灰度值大于阈值,加到总灰度值,数量+1
31 {
32 big_than_th += grayvalue;
33 bigcount++;
34 }
35 else if (grayvalue < Threshold) //如果灰度值小于阈值,加到总灰度值,数量+1
36 {
37 sma_than_th += grayvalue;
38 smacount++;
39 }
40 }
41 }
42 Temp_Threshold = ((big_than_th*1.0 / bigcount) + (sma_than_th*1.0 / smacount)) / 2; //计算新的阈值
43 if (abs(Temp_Threshold - Threshold) < 2) //如果新的阈值和旧的阈值差值的绝对值小于10,则退出
44 break;
45 else
46 Threshold = Temp_Threshold; //否则旧阈值等于新阈值
47 }
48 for (int i = 0; i < height; i++) //对图像进行二值化处理
49 {
50 uchar* data = image.ptr
51 for (int j = 0; j < width; j++)
52 {
53 grayvalue = static_cast
54 if (grayvalue>Threshold)
55 data[j] = 255;
56 else if (grayvalue < Threshold)
57 data[j] = 0;
58 }
59 }
60 }
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C/C+频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号