opencv提供了固定化函数threshold,该函数有5中阈值化类型参数可以选择。
double threshold(InputArray src, OutputArray dst, double thresh, double maxval, int type)
函数解析:
实现图像阈值化操作。参数src表示源图像数组(单通道,8为或者32位浮点数);参数dst表示输出图像组(与输入图像相同的尺寸和类型);thresh表示阈值设置;maxval表示预示最大值,使用THRESH_BINARY或者
THRESH_BINARY_INV类型;type表示阈值化处理的类型设置。
Threshold函数应用在单通道图像中固定阈值处理,通常是为了得到二值化灰度图像(只包含0或者1灰度值)或者为了去除噪声。
代码如下:
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include <stdio.h>
#include <string>
using namespace std;
using namespace cv;
int main()
{
cv::Mat srcImage = cv::imread("C:\\Users\\LP\\Desktop\\C++\\ConsoleApplication4\\ConsoleApplication4\\RGBFlower4.jpg");
if (srcImage.empty())
{
return -1;
}
cv::imshow("原图像", srcImage);
//灰度转换
cv::Mat srcGray;
cv::cvtColor(srcImage, srcGray, CV_RGB2GRAY);
cv::imshow("srcGray", srcGray);
cv::Mat dstImage;
//初始化阈值
int thresh = 130;
//0:二进制阈值,1:反二进制阈值,2:截断阈值,3:0阈值,4:反0阈值
int threshType = 0;
//预设最大值
const int maxVal = 255;
//固定阈值化操作
cv::threshold(srcImage, dstImage, thresh, maxVal, threshType);
cv::imshow("dstImage", dstImage);
cv::waitKey(0);
return 0;
}