opencv学习之路(13)、图像阈值化

时间:2022-02-27 08:44:20

一、图像阈值化简介

opencv学习之路(13)、图像阈值化

二、固定阈值

opencv学习之路(13)、图像阈值化

opencv学习之路(13)、图像阈值化

opencv学习之路(13)、图像阈值化

 三、自适应阈值

opencv学习之路(13)、图像阈值化

opencv学习之路(13)、图像阈值化

 1 #include<opencv2/opencv.hpp>
2 using namespace cv;
3
4 void main(){
5 Mat src=imread("E://1.jpg",0);//以灰度模式读入
6 Mat dst;
7 //threshold(src,dst,100,255,CV_THRESH_BINARY);
8 //adaptiveThreshold(src,dst,255,CV_ADAPTIVE_THRESH_MEAN_C,CV_THRESH_BINARY,11,5);
9 adaptiveThreshold(src,dst,255,CV_ADAPTIVE_THRESH_GAUSSIAN_C,CV_THRESH_BINARY,11,5);
10 imshow("src",src);
11 imshow("dst",dst);
12 waitKey(0);
13 }

opencv学习之路(13)、图像阈值化

 四、滚动条调整参数

 1 #include<opencv2/opencv.hpp>
2 using namespace cv;
3
4 Mat src,dst,dst2;
5 int thres_value=21,block_size=5,c=5;
6
7 void onThreshold(int ,void*){
8 threshold(src,dst,thres_value,255,CV_THRESH_BINARY);
9 imshow("固定阈值",dst);
10 }
11 void onAdaptiveThreshold(int ,void *){
12 if(block_size%2==0) block_size++;//如果block_size是偶数
13 adaptiveThreshold(src,dst2,255,CV_ADAPTIVE_THRESH_GAUSSIAN_C,CV_THRESH_BINARY,block_size,c);
14 imshow("自适应阈值",dst2);
15 }
16
17 void main(){
18 src=imread("E://1.jpg",0);//以灰度模式读入
19 namedWindow("固定阈值",CV_WINDOW_AUTOSIZE);
20 namedWindow("自适应阈值",CV_WINDOW_AUTOSIZE);
21 createTrackbar("Threshold", "固定阈值",&thres_value,255,onThreshold,0);
22 createTrackbar("Block_size", "自适应阈值",&block_size,255,onAdaptiveThreshold,0);
23 createTrackbar("C", "自适应阈值",&c,255,onAdaptiveThreshold,0);
24
25 onThreshold(thres_value,0); //回调函数初始化
26 onAdaptiveThreshold(block_size,0);
27 onAdaptiveThreshold(c,0);
28
29 imshow("src",src);
30 waitKey(0);
31 }

opencv学习之路(13)、图像阈值化