您的位置:首页 > 其它

自适应阈值分割之otsu算法

2013-10-30 19:58 381 查看
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <math.h>
#include <iostream>

#define FLT_EPSILON 1.19209290E-07F // decimal constant
//FLT_EPSILON the minimum positive number such that 1.0 + FLT_EPSILON != 1.0.

using namespace cv;
using namespace std;

double getThreshVal_Otsu_8u( const Mat& _src )
{
Size size = _src.size();
const int N = 256;
int i, j, h
= {0};

unsigned char* src;
for( i = 0; i < size.height; i++ )
{
src = _src.data + _src.step*i;
j = 0;
for(j = 0; j < size.width; j++ )
h[src[j]]++;
}

double mu = 0, scale = 1./(size.width*size.height);
for( i = 0; i < N; i++ )
{
mu += i*(double)h[i];
}

mu *= scale;
double mu1 = 0, q1 = 0;
double max_sigma = 0, max_val = 0;

for( i = 0; i < N; i++ )
{
double p_i, q2, mu2, sigma;

p_i = h[i]*scale;
mu1 *= q1;
q1 += p_i;
q2 = 1. - q1;

if( std::min(q1,q2) < FLT_EPSILON || std::max(q1,q2) > 1. - FLT_EPSILON )
continue;

mu1 = (mu1 + i*p_i)/q1;
mu2 = (mu - q1*mu1)/q2;
sigma = q1*q2*(mu1 - mu2)*(mu1 - mu2);
if( sigma > max_sigma )
{
max_sigma = sigma;
max_val = i;
}
}
return max_val;
}

int main( int argc, char**)
{

Mat src = imread("rice.tif", 0);
Mat dst = Mat::zeros(src.size(), src.type());
namedWindow("dst", 1);
namedWindow("src",1);

int thresh = (int)getThreshVal_Otsu_8u( src );
cout<<"thresh: " << thresh<<endl;
threshold(src, dst, thresh, 255, 0);

imshow("src", src);
imshow("dst", dst);
imwrite("bin.png",dst);
waitKey();

return 0;
}


原图:



结果:



最大类间方差法是由日本学者大津于1979年提出的,是一种自适应的阈值确定的方法,又叫大津

法,简称OTSU。它是按图像的灰度特性,将图像分成背景和目标2部分。背景和目标之间的类间方差

越大,说明构成图像的2部分的差别越大,当部分目标错分为背景或部分背景错分为目标都会导致2部

分差别变小。因此,使类间方差最大的分割意味着错分概率最小。

对于图像I(x,y),前景(即目标)和背景的分割阈值记作T,属于前景的像素点数占整幅图像的比

例记为ω0,其平均灰度μ0;背景像素点数占整幅图像的比例为ω1,其平均灰度为μ1。图像的总平均

灰度记为μ,类间方差记为g。

假设图像的背景较暗,并且图像的大小为M×N,

图像中像素的灰度值小于阈值T的像素个数记作N0,像素灰度大于阈值T的像素个数记作N1,则有:

ω0=N0/ M×N (1)

ω1=N1/ M×N (2)

N0+N1=M×N (3)

ω0+ω1=1 (4)

μ=ω0*μ0+ω1*μ1 (5)

g=ω0(μ0-μ)^2+ω1(μ1-μ)^2 (6)

将式(5)代入式(6),得到等价公式: g=ω0ω1(μ0-μ1)^2 (7)

采用遍历的方法得到使类间方差最大的阈值T,即为所求。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: