1 #include "opencv2/imgproc/imgproc.hpp" 2 #include "opencv2/highgui/highgui.hpp" 3 #include <stdlib.h> 4 #include <stdio.h> 5 6 using namespace cv; 7 8 /// 全局变量定义及赋值 9 10 int threshold_value = 0; 11 int threshold_type = 3;; 12 int const max_value = 255; 13 int const max_type = 4; 14 int const max_BINARY_value = 255; 15 16 Mat src, src_gray, dst; 17 char* window_name = "Threshold Demo"; 18 19 char* trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted"; 20 char* trackbar_value = "Value"; 21 22 /// 自定义函数声明 23 void Threshold_Demo( int, void* ); 24 25 /** 26 * @主函数 27 */ 28 int main( int argc, char** argv ) 29 { 30 /// 读取一副图片,不改变图片本身的颜色类型(该读取方式为DOS运行模式) 31 src = imread( argv[1], 1 ); 32 33 /// 将图片转换成灰度图片 34 cvtColor( src, src_gray, CV_RGB2GRAY ); 35 36 /// 创建一个窗口显示图片 37 namedWindow( window_name, CV_WINDOW_AUTOSIZE ); 38 39 /// 创建滑动条来控制阈值 40 createTrackbar( trackbar_type, 41 window_name, &threshold_type, 42 max_type, Threshold_Demo ); 43 44 createTrackbar( trackbar_value, 45 window_name, &threshold_value, 46 max_value, Threshold_Demo ); 47 48 /// 初始化自定义的阈值函数 49 Threshold_Demo( 0, 0 ); 50 51 /// 等待用户按键。如果是ESC健则退出等待过程。 52 while(true) 53 { 54 int c; 55 c = waitKey( 20 ); 56 if( (char)c == 27 ) 57 { break; } 58 } 59 60 } 61 62 63 /** 64 * @自定义的阈值函数 65 */ 66 void Threshold_Demo( int, void* ) 67 { 68 /* 0: 二进制阈值 69 1: 反二进制阈值 70 2: 截断阈值 71 3: 0阈值 72 4: 反0阈值 73 */ 74 75 threshold( src_gray, dst, threshold_value, max_BINARY_value,threshold_type ); 76 77 imshow( window_name, dst ); 78 }