阈值操作
- OpenCV 提供了 cv::threshold,一共有5种不同的阈值操作
蓝色的横线表示阈值, 红色表示像素值
- Threshold Binary
- Threshold Binary, Inverted
- Truncate
- Threshold to Zero
- Threshold to Zero, Inverted
代码
#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
)