一、图像阈值化简介
二、固定阈值
三、自适应阈值
【示例】
1 //图像的阈值化 2 #include<opencv2/opencv.hpp> 3 using namespace cv; 4 5 int main(){ 6 Mat src=imread("1.jpg",0);//以灰度模式读入 7 Mat dst; 8 //threshold(src,dst,100,255,CV_THRESH_BINARY); 9 //adaptiveThreshold(src,dst,255,CV_ADAPTIVE_THRESH_MEAN_C,CV_THRESH_BINARY,11,5); 10 adaptiveThreshold(src,dst,255,CV_ADAPTIVE_THRESH_GAUSSIAN_C,CV_THRESH_BINARY,11,5); 11 imshow("src",src); 12 imshow("dst",dst); 13 waitKey(0); 14 return 0; 15 }
四、滚动条调整参数
【示例】
1 //添加滚动条调整参数 2 #include<opencv2/opencv.hpp> 3 using namespace cv; 4 5 Mat src,dst,dst2; 6 int thres_value=21,block_size=5,c=5; 7 8 void onThreshold(int ,void*){ 9 threshold(src,dst,thres_value,255,CV_THRESH_BINARY); 10 imshow("固定阈值",dst); 11 } 12 void onAdaptiveThreshold(int ,void *){ 13 if(block_size%2==0) block_size++;//如果block_size是偶数 14 adaptiveThreshold(src,dst2,255,CV_ADAPTIVE_THRESH_GAUSSIAN_C,CV_THRESH_BINARY,block_size,c); 15 imshow("自适应阈值",dst2); 16 } 17 18 int main(){ 19 src=imread("1.jpg",0);//以灰度模式读入 20 namedWindow("固定阈值",CV_WINDOW_AUTOSIZE); 21 namedWindow("自适应阈值",CV_WINDOW_AUTOSIZE); 22 createTrackbar("Threshold", "固定阈值",&thres_value,255,onThreshold,0); 23 createTrackbar("Block_size", "自适应阈值",&block_size,255,onAdaptiveThreshold,0); 24 createTrackbar("C", "自适应阈值",&c,255,onAdaptiveThreshold,0); 25 26 onThreshold(thres_value,0); //回调函数初始化 27 onAdaptiveThreshold(block_size,0); 28 onAdaptiveThreshold(c,0); 29 30 imshow("src",src); 31 waitKey(0); 32 return 0; 33 }