您的位置:首页 > 其它

转载贴--自适应阈值:大津阈值法完全实现

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;
}


这个样子的:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: