OTSU算法的步骤如下:
1、计算灰度图像中每个灰度级的个数Si(i=0,1,2,.....,255);
2、各灰度级占图像中的概率分布Pi=Si/图像的大小(i=0,1,2,......,255);
3、对灰度级进行遍历搜索,计算当前灰度值下前景背景类间概率;
4、通过目标函数计算出类内与类间方差下对应的阈值。
OTSU二值化的实现代码如下:
#include<opencv2\opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int OTSU(Mat SrcImage)
{
int nCols = SrcImage.cols;
int nRows = SrcImage.rows;
int threshold = 0;
//初始化统计参数
int nSumPix[256] ;
float nProDis[256];
for (int i = 0; i < 256; i++) {
nSumPix[i] = 0;
nProDis[i] = 0;
}
//统计灰度级中每个像素在整幅图像中的个数
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nCols; j++) {
nSumPix[(int)SrcImage.at<uchar>(i, j)]++;
}
}
//计算每个灰度级占图像中的概率分布
for (int i = 0; i < 256; i++) {
nProDis[i] = (float)nSumPix[i] / (nCols*nRows);
}
//遍历灰度级【0,255】,计算出最大类间方差下的阈值
float w0, w1, u0_temp, u1_temp, u0, u1, delta_temp;
double delta_max = 0.0;
for (int i = 0; i < 256; i++)
{
//初始化相关参数
w0 = w1 = u0_temp = u1_temp = u0 = u1 = delta_temp = 0;
for (int j = 0; j < 256; j++) {
//背景部分
if (j <= i) {
//当前i为分割阈值,第一类总的概率
w0 += nProDis[j];
u0_temp += j*nProDis[j];
}
//前景部分
else
{
//当前i为分割阈值,第一类总的概率
w1 += nProDis[j];
u1_temp += j*nProDis[j];
}
}
//分别计算各类的平均度
u0 = u0_temp / w0;
u1 = u1_temp / w1;
delta_temp = (float)(w0*w1*pow((u0 - u1), 2));
//依次找到最大类间方差下的阈值
if (delta_temp > delta_max) {
delta_max = delta_temp;
threshold = i;
}
}
return threshold;
}
int main() {
Mat srcImage, imageGray;
srcImage = imread("D:/VSproject/tupian/1(1).jpg");
if (!srcImage.data)return 0;
cvtColor(srcImage, imageGray, CV_RGB2GRAY);
int otsuThreshold = OTSU(imageGray);
cout << "otsu阈值: "<<otsuThreshold << endl;
Mat otsuResultImage(imageGray.size(), CV_8UC1);
for (int i = 0; i < imageGray.rows; i++) {
uchar *p = otsuResultImage.ptr<uchar>(i);
for (int j = 0; j < imageGray.cols; j++) {
if (imageGray.at<uchar>(i,j) > otsuThreshold)p[j] = 255;
else
p[j] = 0;
}
}
imshow("input", srcImage);
imshow("otsuResultImage", otsuResultImage);
waitKey(0);
return 0;
}
实现效果如下: