图像二值化分割,最重要的就是计算阈值
阈值计算的方法有很多,基本分为两类,全局阈值和自适应阈值
全局分割方法
1.均值法
2.OTSU阈值
原理图
直方图分割,计算各个部分的方差 按比重求方差的最小值
3.三角阈值
原理图
API调用
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
int main() {
Mat src = imread("D:/ps/jisoo.png");
if (src.empty())
{
cout << "could not find the image";
return -1;
}
namedWindow("input", WINDOW_FREERATIO);
imshow("input", src);
//阈值计算算法很多,基本分为两类, 全局阈值与自适应阈值
Mat gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
imshow("gray", gray);
Scalar m = mean(gray);//就均值
cout << "mean :" << m[0];
threshold(gray, binary, m[0], 255, THRESH_BINARY);
imshow("binary1", binary);
//OTSU阈值分割 一般优先选这个
double t1=threshold(gray, binary, m[0], 255, THRESH_BINARY|THRESH_OTSU);
imshow("binary2", binary);
//三角法
double t2 = threshold(gray, binary, m[0], 255, THRESH_BINARY|THRESH_TRIANGLE);
imshow("binary3", binary);
cout << t1 << endl;
cout << t2 << endl;
waitKey(0);
destroyAllWindows();
return 0;
}