图像阈值(threshold)
- 简单点说是把图像分割的标尺,这个标尺是根据什么产生的,阈值产生算法?阈值类型。(Binary segmentation)二进制分割
- OpenCV提供函数
cv :: threshold
来执行阈值操作。

- src_gray:我们的输入图片
- dst:目标(输出)图像
- threshold_value:进行阈值操作的阈值
- max_BINARY_value:二进制阈值操作使用的值(设置所选像素)
- threshold_type:5个阈值操作之一。
- 在阈值类型前,怎么寻找阈值? 除了主动输入,还可以用 THRESH_OTSU 、 THRESH_TRIANGLE 两种opencv提供的算法产生阈值(只适用于颜色数据是8位的图像,否则报错)
1. 阈值类型一阈值二值化(threshold binary)
- 左下方的图表示图像像素点Src(x,y)值分布情况,蓝色水平线表示阈值

2. 阈值类型一阈值反二值化(threshold binary Inverted)
- 左下方的图表示图像像素点Src(x,y)值分布情况,蓝色水平线表示阈值

3. 阈值类型一截断 (truncate)
- 左下方的图表示图像像素点Src(x,y)值分布情况,蓝色水平线表示阈值

4. 阈值类型一阈值取零 (threshold to zero)
- 左下方的图表示图像像素点Src(x,y)值分布情况,蓝色水平线表示阈值

5. 阈值类型一阈值反取零 (threshold to zero inverted)
- 左下方的图表示图像像素点Src(x,y)值分布情况,蓝色水平线表示阈值

总结

代码示例
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
Mat src,gray_src,dst;
char input_win[]="Input Windows",output_win[]="Output Windows";
int threshold_type=3,threshold_value=0;
int const max_value=255,max_type=4;
void Threshold_Demo(int, void* );
int main(){
src=imread("E:/Experiment/OpenCV/Pictures/dog2.jpg");
if(src.empty()){
printf("could not load image...");
return -1;
}
namedWindow(input_win,CV_WINDOW_AUTOSIZE);
namedWindow(output_win,CV_WINDOW_AUTOSIZE);
imshow(input_win,src);
cvtColor(src,gray_src,CV_BGR2GRAY);
createTrackbar("阈值类型:",output_win, &threshold_type, max_type, Threshold_Demo);
createTrackbar("阈值大小:",output_win, &threshold_value, max_value, Threshold_Demo);
Threshold_Demo(0,0);
Mat dst1,dst2;
int threshold_max=255;
threshold(gray_src, dst1, threshold_value, threshold_max, THRESH_OTSU | threshold_type);
imshow("THRESH_OTSU", dst1);
threshold(gray_src, dst2, threshold_value, threshold_max, THRESH_TRIANGLE| threshold_type);
imshow("THRESH_TRIANGLE", dst2);
waitKey(0);
return 0;
}
void Threshold_Demo(int, void*){
threshold(gray_src, dst, threshold_value, 255, threshold_type);
imshow(output_win, dst);
}
运行截图

参考博客
- https://blog.****.net/huanghuangjin/article/details/80962043
- https://blog.****.net/LYKymy/article/details/83154291