具体的公式推导参见冈萨雷斯***《数字图像处理》***
Otsu方法又称最大类间方差法,通过把像素分配像素分为两类或多类,计算类间方差,当方差达到最大值时,类分割线(即灰度值)就作为图像分割阈值。Otsu还有一个重要的性质,即它完全基于对图像直方图进行计算,这也使他成为最常用的阈值处理算法之一。
算法步骤如下: Otsu只有在直方图呈现双峰的时候才会有一个很好的效果,在直方图单峰或多峰的情况下效果不是很好,那就需要通过实际情况来选取其他的方法来得到预期的分割效果。
代码如下;
int main()
{
string path = "F:\\Speedlimit\\RGBCutImages1\\14.jpg";
Mat SrcImage = imread(path);
if (!SrcImage.data) {
std::cout << "Could not open or find the image" << std::endl;
return -1;
}
cvtColor(SrcImage, SrcImage, COLOR_BGR2GRAY);
cv::Mat ThreImage, OtsuImage;
cv::Mat gray_hist;
const int histSize = 256;
float range[] = { 0, 256 };
const float* histRange[] = { range };
bool uniform = true, accumulate = false;
calcHist(&SrcImage, 1, 0, Mat(), gray_hist, 1, &histSize, histRange, uniform, accumulate);
cv::Mat norm_gray_hist = cv::Mat::zeros(gray_hist.size(), gray_hist.type());
for (int i = 0; i < histSize; ++i)
{
norm_gray_hist.at<float>(i) = gray_hist.at<float>(i) / SrcImage.total();
}
Mat mat_mean, mat_stddev;
double gray_mean, gray_sigma;
meanStdDev(SrcImage, mat_mean, mat_stddev);
gray_mean = mat_mean.at<double>(0, 0);
gray_sigma = mat_stddev.at<double>(0, 0) * mat_stddev.at<double>(0, 0);
std::vector<double>sigma_ks(histSize);
for (int k = 0; k < histSize; ++k)
{
double p1 = 0.0;
double m_k = 0.0;
for (int i = 0; i <= k; ++i)
{
p1 += norm_gray_hist.at<float>(i);
m_k += i * norm_gray_hist.at<float>(i);
}
if (p1 == 0.f || (1 - p1) == 0.f)
sigma_ks[k] = 0.0;
else
sigma_ks[k] = (gray_mean * p1 - m_k) * (gray_mean * p1 - m_k) / (p1 * (1 - p1));
}
double max_Sigma_k = 0.0;
std::vector<int>maxval_Ts;
int Threshold_T = 0;
for (int i = 0; i < sigma_ks.size(); ++i)
{
if (sigma_ks[i] > max_Sigma_k)
max_Sigma_k = sigma_ks[i];
}
for (int i = 0; i < sigma_ks.size(); ++i)
{
if (max_Sigma_k == sigma_ks[i])
maxval_Ts.push_back(i);
}
for (int i = 0; i < maxval_Ts.size(); ++i)
Threshold_T += maxval_Ts[i];
Threshold_T = Threshold_T / maxval_Ts.size();
cout << Threshold_T << endl;
threshold(SrcImage, ThreImage, Threshold_T, 255, THRESH_BINARY);
threshold(SrcImage, OtsuImage, 0, 255, THRESH_OTSU);
imshow("src", SrcImage);
cv::waitKey(0);
return 0;
}
处理结果:
新手上路,代码仅作为参考,下一期更新***可使用掩模功能的大津阈值法***。
|