一、基本阈值操作
opencv提供了threshold()函数对图像的阈值进行处理,threshold()共支持五种类型的阈值化方式,分别是阈值二值化、阈值反二值化、截断、阈值取零和阈值反取零。
- 阈值二值化 threshold binary
- 阈值反二值化 threshold binary inverted
- 截断 truncate
- 阈值取零 threshold to zero
- 阈值反取零 threshold to zero inverted
二、threshold()
double cv::threshold ( InputArray src,
OutputArray dst,
double thresh,
double maxval,
int type
)
- InputArray src: 输入图像,可以是Mat类型,图像必须为单通道8位或32位浮点型图像
- OutputArray dst: 输出图像,与输入图像尺寸和类型相同
- double thresh: 设定的阈值
- double maxval: 使用THRESH_BINARY和THRESH_BINARY_INV类型的最大值
- int type: 阈值化类型
三、示例
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
Mat src, dst, gray_src;
int threshold_value = 127;
int threshold_max = 255;
const char* output_title = "binary image";
void Threshold_Demo(int, void*);
int main()
{
src = imread("images/02.png");
if (!src.data) {
cout << "could not load image1..." << endl;
return -1;
}
namedWindow("input_image", CV_WINDOW_AUTOSIZE);
imshow("input_image", src);
Threshold_Demo(0, 0);
createTrackbar("Threshold Value:", output_title, &threshold_value, threshold_max, Threshold_Demo);
waitKey();
return 0;
}
void Threshold_Demo(int, void*)
{
cvtColor(src, gray_src, CV_BGR2GRAY);
threshold(gray_src, dst, threshold_value,threshold_max,THRESH_BINARY);
imshow(output_title, dst);
}