Ostu(大津法)二值化图像算法/最佳全局阈值
介绍
最大类间方差法是由日本学者大津于1979年提出的,是一种自适应的阈值确定的方法,又叫大津
法,简称OTSU。它是按图像的灰度特性,将图像分成背景和目标2部分。背景和目标之间的类间方差
越大,说明构成图像的2部分的差别越大,当部分目标错分为背景或部分背景错分为目标都会导致2部
分差别变小。因此,使类间方差最大的分割意味着错分概率最小。
算法原理
该算法主要包括一下几个步骤:
- 先计算图像的直方图,即将图像所有的像素点按照0~255共256个bin,统计落在每个bin的像素点数量,这个很简单啦~
- 归一化直方图,也即将每个bin中像素点数量除以总的像素点,使其限制在0~1之间
- 在这里设置一个分类的阈值ii<script type="math/tex" id="MathJax-Element-934">i</script>,也即一个灰度级,开始从0迭代
通过归一化的直方图,统计0~i 灰度级的像素(假设像素值在此范围的像素叫做前景像素) 所占整幅图像的比例<script type="math/tex" id="MathJax-Element-935">w_0</script>,并统计前景像素的平均灰度u0u0<script type="math/tex" id="MathJax-Element-936">u_0</script>;统计i~255灰度级的像素(假设像素值在此范围的像素叫做背景像素) 所占整幅图像的比例w1w1<script type="math/tex" id="MathJax-Element-937">w_1</script>,并统计背景像素的平均灰度u1u1<script type="math/tex" id="MathJax-Element-938">u_1</script>;在这里,设图像的总平均灰度为u2u2<script type="math/tex" id="MathJax-Element-939">u_2</script>,类间方差记为gg<script type="math/tex" id="MathJax-Element-940">g</script>。
其中:
<script type="math/tex" id="MathJax-Element-941">u_2=ω_0*u_0+ω_1*u_1</script>,g=ω0(u0−μ2)2+ω1(u1−u2)2g=ω0(u0−μ2)2+ω1(u1−u2)2<script type="math/tex" id="MathJax-Element-942">g=ω_0(u_0-μ_2)^2+ω_1(u_1-u_2)^2</script> 将u2u2<script type="math/tex" id="MathJax-Element-943">u_2</script>带入gg<script type="math/tex" id="MathJax-Element-944">g</script>中,可得:
<script type="math/tex" id="MathJax-Element-945">g=ω_0ω_1(u_0-u_1)^2</script> ++ii<script type="math/tex" id="MathJax-Element-946">i</script>,阈值的灰度值加1,并转到第4个步骤,直到i为256时结束迭代
- 将最大<script type="math/tex" id="MathJax-Element-947">g</script>相应的ii值作为图像的全局阈值
源代码
注意:这里opencv已经实现该算法,可以直接调用
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat img = imread("C:\\Users\\18301\\Desktop\\1.jpg");
if (img.empty())
{
cout << "Error: Could not load image" << endl;
return 0;
}
Mat gray;
cvtColor(img, gray, CV_BGR2GRAY);
Mat dst;
threshold(gray, dst, 0, 255, CV_THRESH_OTSU);
imshow("src", img);
imshow("gray", gray);
imshow("dst", dst);
waitKey(0);
return 0;
}
实验结果

更多推荐

所有评论(0)