转载贴--自适应阈值:大津阈值法完全实现
2015-12-03 21:47
369 查看
具体算法的实现请看转载:/article/8436483.html
博主写的挺好。
以下是我实现的过程:
这个样子的:
博主写的挺好。
以下是我实现的过程:
/************************************************************************/ // author:冒失的鱼 // version:vs2010+opencv2.4.10 /************************************************************************/ #include <iostream> #include <opencv/cv.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> int otsuThreshold(IplImage* img) { int T = 0;//阈值 int height = img->height; int width = img->width; int step = img->widthStep; int channels = img->nChannels; uchar* data = (uchar*)img->imageData; double gSum0;//第一类灰度总值 double gSum1;//第二类灰度总值 double N0 = 0;//前景像素数 double N1 = 0;//背景像素数 double u0 = 0;//前景像素平均灰度 double u1 = 0;//背景像素平均灰度 double w0 = 0;//前景像素点数占整幅图像的比例为ω0 double w1 = 0;//背景像素点数占整幅图像的比例为ω1 double u = 0;//总平均灰度 double tempg = -1;//临时类间方差 double g = -1;//类间方差 double Histogram[256]={0};// = new double[256];//灰度直方图 double N = width*height;//总像素数 for(int i=0;i<height;i++) {//计算直方图 for(int j=0;j<width;j++) { double temp = data[i*step + j * 3] * 0.114 + data[i*step + j * 3+1] * 0.587 + data[i*step + j * 3+2] * 0.299; temp = temp<0? 0:temp; temp = temp>255? 255:temp; Histogram[(int)temp]++; } } //计算阈值 for (int i = 0;i<256;i++) { gSum0 = 0; gSum1 = 0; N0 += Histogram[i]; N1 = N-N0; if(0==N1)break;//当出现前景无像素点时,跳出循环 w0 = N0/N; w1 = 1-w0; for (int j = 0;j<=i;j++) { gSum0 += j*Histogram[j]; } u0 = gSum0/N0; for(int k = i+1;k<256;k++) { gSum1 += k*Histogram[k]; } u1 = gSum1/N1; //u = w0*u0 + w1*u1; g = w0*w1*(u0-u1)*(u0-u1); if (tempg<g) { tempg = g; T = i; } } return T; } int main() { cv::Mat img,image; //img = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1); img = cv::imread("test.jpg"); cvtColor(img,image,CV_BGR2GRAY); IplImage iplimage = image; int T; int width = image.rows; int height = image.cols; double time_cost = static_cast<double>(cv::getTickCount()); T = otsuThreshold(&iplimage); for (int i=0;i<width;i++) { uchar *data = image.ptr<uchar>(i); for (int j=0;j<height;j++) { if (data[i,j]>T) { data[i,j] = 255; } else { data[i,j] = 0; } } } imshow("Image",image); time_cost = ((double)cv::getTickCount() - time_cost)/(cv::getTickFrequency()); std::cout<<"运行时间:"<<time_cost<<"s"<<std::endl; cv::waitKey(0); return 0; }
这个样子的:
相关文章推荐
- 根据URI获取文件的绝对路径
- Android SDK 在线更新镜像服务器资源
- webrtc(二) ns
- http文件头详解http://www.cnblogs.com/tiwlin/archive/2009/09/06/1561279.html
- 关于Intent的使用
- 预处理
- UISegmentedControl
- dedecms织梦特定条件下,隐藏特定栏目的方法,通过css实现
- codeforces604C Alternative Thinking (脑洞大开 )
- 浅谈面向对象(java)
- EM 算法在GMM中的应用
- 日记
- Android集成支付宝
- qmake编译选项的控制(debug|release)
- 一些漂亮的js库
- Android之mvp和mvc对比分析以及实际应用
- 练习E-5
- Android第三方开源FloatingActionButton(com.getbase.floatingactionbutton)【1】
- 图的搜索
- 京东咚咚架构演进