目录
1.cv::threshold
对于每个像素,应用相同的阈值。如果像素值小于阈值,则将其设置为0,否则将其设置为最大值。函数cv::threshold用于应用阈值。
threshold(in, out, double thresh,double maxval,int type);
参数1是源图像,它应该是灰度图像。
参数2是输出图像
参数3是阈值,用于对像素值进行分类。
参数4是分配给超过阈值的像素值的最大值。
OpenCV提供了不同类型的阈值,这由函数的第5个参数给出。所有简单的阈值类型为:
cv::THRESH_BINARY
cv::THRESH_BINARY_INV
cv::THRESH_TRUNC
cv::THRESH_TOZERO
cv::THRESH_TOZERO_INV
Otsu的方法避免了必须选择一个值并自动确定它的情况。
详情见:https://blog.csdn.net/guduruyu/article/details/68059450
#include<opencv2/opencv.hpp>
#include<iostream>
#include<imgproc.hpp>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
Mat image = imread("C:/Users/YY/Pictures/Saved Pictures/1.jpg",IMREAD_GRAYSCALE);
Mat out;
//全局阈值
threshold(image, out, 100.0,255,THRESH_BINARY);
//Otsu阈值
double i;
i= threshold(image, out, 0, 255, THRESH_BINARY + THRESH_OTSU);//返回的阈值
imshow("显示", out);
waitKey(0);
destroyAllWindows();
return 0;
}
![](https://img-blog.csdnimg.cn/20210623225018389.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQyMzQ0MTMy,size_16,color_FFFFFF,t_70)
2.cv::adaptiveThreshold
如果图像在不同区域具有不同的光照条件。在这种情况下,自适应阈值阈值化可以提供帮助
adaptiveThreshold(
cv::InputArray src, // 输入图像
cv::OutputArray dst, // 输出图像
double maxValue, // 向上最大值
int adaptiveMethod, // 自适应方法,平均或高斯
int thresholdType // 阈值化类型
int blockSize, // 附近区域大小,3,5,7and so on
double C // 常量
);
自适应方法:
cv.ADAPTIVE_THRESH_MEAN_C::阈值是邻近区域的平均值减去常数C。
cv.ADAPTIVE_THRESH_GAUSSIAN_C:阈值是邻域值的高斯加权总和减去常数C。
int main(int argc, char** argv) {
Mat image = imread("C:/Users/YY/Pictures/Saved Pictures/1.jpg",IMREAD_GRAYSCALE);
Mat out;
adaptiveThreshold(image, out, 255,ADAPTIVE_THRESH_GAUSSIAN_C,THRESH_BINARY,5,2);
imshow("显示", out);
waitKey(0);
destroyAllWindows();
return 0;
}