根据《面向飞机蒙皮接缝的线结构光检测技术研究_张卡》论文中的原理,编写了自适应阈值函数
原理:
1 //计算灰度最大最小值 2 void MaxGrayValue(Mat image,int &max,int &min) 3 { 4 max = 0; 5 min = 255; 6 Mat *im = reinterpret_cast<Mat*>((void*)&image); 7 int height = image.rows; 8 int width = image.cols; 9 int N = height * width; 10 //cout << "125" << " " << "125" << " " << static_cast<int>(im->at<uchar>(Point(182, 190))) << endl; 11 for (int i = 0; i < height; i++) 12 { 13 for (int j = 0; j < width; j++) 14 { 15 if ((static_cast<int>(im->at<uchar>(Point(j, i))))>max) 16 max = static_cast<int>(im->at<uchar>(Point(j, i))); 17 else if ((static_cast<int>(im->at<uchar>(Point(j, i))))<min) 18 min = static_cast<int>(im->at<uchar>(Point(j, i))); 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<Mat*>((void*)&image); //获取像素点信息 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<int>(im->at<uchar>(Point(j, i))); //获取指定点灰度值 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<uchar>(i); 51 for (int j = 0; j < width; j++) 52 { 53 grayvalue = static_cast<int>(im->at<uchar>(Point(j, i))); 54 if (grayvalue>Threshold) 55 data[j] = 255; 56 else if (grayvalue < Threshold) 57 data[j] = 0; 58 } 59 } 60 }
原文地址:https://www.cnblogs.com/Summerio/p/8280905.html
时间: 2024-10-14 11:51:36