OpenCV第七讲:阈值的作用
阈值可以被视作最简单的图像分割方法。利用阈值进行分割的方法是基于图像中物体和背景之间的灰度差异来实现的。
1. 阈值化操作
-
固定阈值操作
Threshold() 函数
-
自适应阈值操作
adaptiveThreshold()函数
-
源代码分析
/***************************************************************************
* double threshold( InputArray src, OutputArray dst,
double thresh, double maxval, int type );
* void adaptiveThreshold( InputArray src, OutputArray dst,
double maxValue, int adaptiveMethod,
int thresholdType, int blockSize, double C );
*
adaptiveMethod() : 自适应阈值的方法
threshold(): 固定阈值法
* adaptiveMethod:
* enum AdaptiveThresholdTypes {
ADAPTIVE_THRESH_MEAN_C = 0,
ADAPTIVE_THRESH_GAUSSIAN_C = 1
};
*
* thresholdType:
* enum ThresholdTypes {
THRESH_BINARY = 0, // 二值阈值化
THRESH_BINARY_INV = 1, // 二值阈值化并反转
THRESH_TRUNC = 2, // 截断阈值化
THRESH_TOZERO = 3, // 超过阈值被置0
THRESH_TOZERO_INV = 4, // 低于阈值被置0
THRESH_MASK = 7,
THRESH_OTSU = 8, //
THRESH_TRIANGLE = 16 //
};
****************************************************************************/
2. 程序测试
- 程序源码
#include <opencv2/opencv.hpp>
#define WINDOW_NAME "Threshold"
using namespace cv;
int m_ThresholdType = 0;
int m_ThresholdMethod = 0;
int m_ThresholdValues = 50;
Mat img, sholdImage;
void on_Threshold(int, void*);
int main(int argc, char** argv)
{
if(! argc ==2)
{
std::cerr<<"please run ./Binary ../cfg/timg2.jpeg \n";
}
string filename = argv[1];
Mat srcImage = imread(filename,1);
imshow("srcImage", srcImage);
waitKey(1);
namedWindow(WINDOW_NAME, 1);
srcImage.copyTo(img);
createTrackbar("ThresholdMethod", WINDOW_NAME, &m_ThresholdMethod, 1, on_Threshold);
createTrackbar("ThresholdType", WINDOW_NAME, &m_ThresholdType, 1, on_Threshold);
// createTrackbar("ThresholdValues", WINDOW_NAME, &m_ThresholdValues, 255, on_Threshold());
on_Threshold(0, 0);
while(1)
{
int key;
key = waitKey(10);
if((char)key == 27)
{
break;
}
}
}
//cv::ThresholdTypes;
void on_Threshold(int, void*)
{
if(img.channels() == 3)
{
cvtColor(img, img, COLOR_BGR2GRAY);
}
adaptiveThreshold(img, sholdImage, 255, m_ThresholdMethod, m_ThresholdType, 3, 3.0);
imshow(WINDOW_NAME, sholdImage);
}
- 测试结果