OPENCV系列博客主要记录自己学习OPENCV的历程,以及存储已经实现的代码,以备后续回顾使用,代码中包含了主要的备注。
一. 图像阈值
1 定义: 其实就是将图像进行分割的标尺。
2 阈值类型 1(阈值二值化/反二值化)
这个阈值类型: 大于某个值,设为0或1; 小于的设为相反的值。
2 阈值类型 2(截断)
3 阈值类型3(阈值取0)
二. 图像阈值相关API
2.1 如何查找设置阈值:OpenCV提供了查找阈值的方法
下图中:上边5条是阈值的处理方法,下边的是自动查找阈值的方法。
注意!!使用阈值方法,需要输入灰度图!!!
三.实现代码(注意threshold方法,threshold的阈值设置方法!!)
#include <opencv2/opencv.hpp>
#include <iostream>
#include "math.h"
using namespace std;
using namespace cv;
Mat src,dst,gray_src;
int threshold_value = 127;
int threshold_max = 255;
int type_num = 2;
int type_max = 4;
const char* output_title = "binary_iamge";
void Threshold_demo(int,void*);
int main(int argc, char** argv) {
//Step1 读取图片
src = imread("E:/OpenCVLearning/Project/source_image/sample.jpg"); //注意斜线方向
if (!src.data) {
cout << "Could not load the image ...." << endl;
return -1;
}
namedWindow("input_image",CV_WINDOW_AUTOSIZE);
imshow("input_image",src);
//step3 创建GUI 拖动条
namedWindow(output_title, CV_WINDOW_AUTOSIZE);
createTrackbar("Threshold value", output_title, &threshold_value, threshold_max, Threshold_demo); //(显示窗口名,受控阈值,阈值最大,调整阈值时运行的子程序)
createTrackbar("Type value", output_title, &type_num, type_max, Threshold_demo); // 这个是用来切换使用不同阈值的方法
//step4 运行Threshold的程序
Threshold_demo(0,0);
waitKey(0);
return 0;
}
void Threshold_demo(int, void*) {
//step2 将图片转化为灰度图
cvtColor(src, gray_src, CV_RGB2GRAY);
threshold(gray_src, dst, threshold_value, threshold_max, type_num); //!!(输入,输出,阈值大小,阈值方法)
//threshold(gray_src, dst, 0, 255, THRESH_OTSU | type_num); //!!自动查找阈值!!!!
imshow(output_title,dst);
}
四.效果