【OpenCV】基本阈值操作
图像阈值(threshold)
阈值 是什么?简单点说是把图像分割的标尺,这个标尺是根据什么产生的,阈值产生算法?阈值类型。(Binary segmentation)
1 阈值类型一阈值二值化(threshold binary)
表示图像像素点Src(x,y)值分布情况,蓝色水平线表示阈值
2 阈值类型一阈值反二值化(threshold binary Inverted)
3 阈值类型一截断 (truncate)
4 阈值类型一阈值取零 (threshold to zero)
5 阈值类型一阈值反取零 (threshold to zero inverted)
代码实现
#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
using namespace std;
Mat src, gray_src,dst1,dst2;
void threshold_demo(int, void*);
int threshold_value = 127;
int threshold_max = 255;
const char* winname = "threshold";
int type_value = 2;
int type_max = 4;
int main(int argc, char** argv)
{
src = imread("1.jpg");
if (!src.data) {
cout << "can not load the image..." << endl;
return -1;
}
namedWindow("input", CV_WINDOW_AUTOSIZE);
imshow("input", src);
namedWindow(winname, CV_WINDOW_AUTOSIZE);
createTrackbar("threshold value", winname, &threshold_value, threshold_max, threshold_demo);//阈值滑动条
createTrackbar("type_value", winname, &type_value, type_max, threshold_demo);//阈值化方法滑动条
threshold_demo(0, 0);
waitKey(0);
return 0;
}
void threshold_demo(int,void*) {
cvtColor(src, gray_src, CV_BGR2GRAY);
threshold(gray_src, dst1, threshold_value, threshold_max, type_value);
imshow(winname, dst1);
threshold(gray_src, dst2, 0, 255, THRESH_OTSU);//同理,THRESH_TRIANGLE
imshow("自动寻找阈值", dst2);
}
实验结果
原图
阈值操作
自动寻找阈值 THRESH_OTSU/THRESH_TRIANGLE