轉載自 http://blog.csdn.net/timidsmile/article/details/8493468
otsu法(最大類間方差法,有時也稱之爲大津算法)使用的是聚類的思想,把圖像的灰度數按灰度級分成2個部分,使得兩個部分之間的灰度值差異最大,每個部分之間的灰度差異最小,通過方差的計算來尋找一個合適的灰度級別 來劃分。 所以 可以在二值化的時候 採用otsu算法來自動選取閾值進行二值化。otsu算法被認爲是圖像分割中閾值選取的最佳算法,計算簡單,不受圖像亮度和對比度的影響。因此,使類間方差最大的分割意味着錯分概率最小。
設t爲設定的閾值。
wo: 分開後 前景像素點數佔圖像的比例
uo: 分開後 前景像素點的平均灰度
w1:分開後 被景像素點數佔圖像的比例
u1: 分開後 被景像素點的平均灰度
u=w0*u0 + w1*u1 :圖像總平均灰度
從L個灰度級遍歷t,使得t爲某個值的時候,前景和背景的方差最大, 則 這個 t 值便是我們要求得的閾值。
其中,方差的計算公式如下:
g=wo * (uo - u) * (uo - u) + w1 * (u1 - u) * (u1 - u)
[ 此公式計算量較大,可以採用: g = wo * w1 * (uo - u1) * (uo - u1) ]
由於otsu算法是對圖像的灰度級進行聚類,so 在執行otsu算法之前,需要計算該圖像的灰度直方圖。
按照上面的解釋參考代碼如下:
#include "stdafx.h"
#include "stdio.h"
#include "cv.h"
#include "highgui.h"
#include "Math.h"
int Otsu(IplImage* src);
int _tmain(int argc, _TCHAR* argv[])
{
IplImage* img = cvLoadImage("c:\\aSa.jpg",0);
IplImage* dst = cvCreateImage(cvGetSize(img), 8, 1);
int threshold = Otsu(img);
printf("threshold = %d\n", threshold);
cvThreshold(img, dst, threshold, 255, CV_THRESH_BINARY);
cvNamedWindow( "img", 1 );
cvShowImage("img", dst);
cvWaitKey(-1);
cvReleaseImage(&img);
cvReleaseImage(&dst);
cvDestroyWindow( "dst" );
return 0;
}
int Otsu(IplImage* src)
{
int height=src->height;
int width=src->width;
//histogram
float histogram[256] = {0};
for(int i=0; i < height; i++)
{
unsigned char* p=(unsigned char*)src->imageData + src->widthStep * i;
for(int j = 0; j < width; j++)
{
histogram[*p++]++;
}
}
//normalize histogram
int size = height * width;
for(int i = 0; i < 256; i++)
{
histogram[i] = histogram[i] / size;
}
//average pixel value
float avgValue=0;
for(int i=0; i < 256; i++)
{
avgValue += i * histogram[i]; //整幅圖像的平均灰度
}
int threshold;
float maxVariance=0;
float w = 0, u = 0;
for(int i = 0; i < 256; i++)
{
w += histogram[i]; //假設當前灰度i爲閾值, 0~i 灰度的像素(假設像素值在此範圍的像素叫做前景像素) 所佔整幅圖像的比例
u += i * histogram[i]; // 灰度i 之前的像素(0~i)的平均灰度值: 前景像素的平均灰度值
float t = avgValue * w - u;
float variance = t * t / (w * (1 - w) );
if(variance > maxVariance)
{
maxVariance = variance;
threshold = i;
}
}
return threshold;
}