1 图像阈值
图像阈值是一种图像处理技术,用于将图像转换为二值图像。通过设定一个阈值,将图像中的像素值与阈值进行比较,将大于或小于阈值的像素分别设置为不同的像素值,从而实现图像的二值化处理。
2 阈值类型
2-1 阈值类型-阈值二值化(threshold binary)
2-2 阈值类型-阈值反二值化(threshold binary Inverted)
2-3 阈值类型-截断(truncate)
2-4 阈值类型-阈值取零(threshold to zero)
2-5 阈值类型-阈值反取零(threshold to zero inverted)
2-6 自动计算阈值:THRESH_OTSU
使用Otsu算法选择最佳阈值
2-7 自动计算阈值:THRESH_TRIANGLE
使用三角算法选择最佳阈值
3 代码演示
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
Mat src,gray_src, dst;
int threshold_value = 127;
int threshold_max = 255;
int type = 1;
int type_max = 4;
const char *WINDNAME = "binary image";
void Threshold_demo(int, void*) {
cvtColor(src, gray_src, CV_RGB2GRAY);
threshold(gray_src, dst, threshold_value, threshold_max, type);
//threshold(gray_src, dst, threshold_value, threshold_max, THRESH_OTSU| type);
//threshold(gray_src, dst, threshold_value, threshold_max, THRESH_TRIANGLE | type);
imshow(WINDNAME, dst);
}
int main(int argc, char** argv)
{
src = imread("./1.png");
if (!src.data) //判断图片是否加载成功!
{
std::cout << "打开图片失败!" << std::endl;
return -1;
}
imshow("src image", src);
namedWindow(WINDNAME,WINDOW_AUTOSIZE);
createTrackbar("threshold value:", WINDNAME, &threshold_value, threshold_max, Threshold_demo);
createTrackbar("type is:", WINDNAME, &type, type_max, Threshold_demo);
waitKey(100000);
return 0;
}