阈值操作
- OpenCV 提供了 cv::threshold,一共有5种不同的阈值操作
蓝色的横线表示阈值, 红色表示像素值
![](https://i-blog.csdnimg.cn/blog_migrate/47aac71d0615afab94600400dde74613.png)
- Threshold Binary
![](https://i-blog.csdnimg.cn/blog_migrate/3d9c827f3c6d397be6ec0de0d5d15788.png)
- Threshold Binary, Inverted
![](https://i-blog.csdnimg.cn/blog_migrate/aaf4b5a62facf2ded8f4c11778e7be6d.png)
- Truncate
![](https://i-blog.csdnimg.cn/blog_migrate/362db74eb052b9c687f2d2f367f887a6.png)
- Threshold to Zero
![](https://i-blog.csdnimg.cn/blog_migrate/3f744b1e9ba24d6c7d58f495e71afb14.png)
- Threshold to Zero, Inverted
![](https://i-blog.csdnimg.cn/blog_migrate/a5dcbfdbdcd405fd6535767b89bdf04f.png)
代码
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
//trackbar 初始值和最大值
int threshold_value = 0;
int threshold_type = 3;
int const max_value = 255;
int const max_type =4;
int const max_pixel_value =255;
// trackbar的名字
const char* trackbar_type = "Type: \n 0:Binary\n1: Binary Inverted\n2:Truncate \n3:To zero\n4:Zero Inverted";
const char* trackbar_value = "Value";
String window_name("Threshold_Demo");
String image_name("../res/beauty.jpg");
Mat src,dst,src_gray;
void Threshold_Demo(int arg1, void* arg2);
int main(void)
{
src = imread(image_name);
if(src.empty())
{
cout << "can't load the image" << endl;
}
cv::cvtColor(src,src_gray,cv::COLOR_BGR2GRAY);
cv::namedWindow(window_name,cv::WINDOW_AUTOSIZE);
cv::createTrackbar(trackbar_type,window_name,&threshold_type,max_type,Threshold_Demo);
cv::createTrackbar(trackbar_value,window_name,&threshold_value,max_value,Threshold_Demo);
Threshold_Demo(0,0);
waitKey();
return 0;
};
void Threshold_Demo(int arg1, void* arg2)
{
threshold(src_gray,dst,threshold_value,max_pixel_value,threshold_type);
imshow(window_name,dst);
}
结果:
OpenCV API
- double cv::threshold
(
InputArray src,
OutputArray dst,
double thresh, // 阈值
double maxval, // 最大值
int type , // 阈值处理的类型,上面5种方式
)
- int cv::createTrackbar
(
const String & trackbarname,
const String & winname,
int * value, // 初始值
int count, //最大值
TrackbarCallback onChange = 0, //回调函数名(必须申明成 void Foo(int,void*); )
void * userdata = 0
)