您的位置:首页 > 运维架构

opencv学习(二十九)之灰度图转化为二值图adaptiveThreshold

2017-01-20 12:12 253 查看
针对图像的阈值操作,opencv除了提供threshold函数也提供了adaptiveThreshold()函数,从字面意思可以翻译为自适应阈值操作,函数的主要功能是将灰度图转化为二值图像。其函数原型如下:

void cv::adaptiveThreshold  ( InputArray  src,
OutputArray  dst,
double  maxValue,
int  adaptiveMethod,
int  thresholdType,
int  blockSize,
double  C
)


参数解释:

. InputArray src: 输入图像,8位单通道图像

. OutputArray dst: 目标图像,与输入图像有相同的尺寸和类型

. double maxValue: 给像素赋予的满足阈值类型的非零值

. int adaptiveMethod: 用于指定自适应阈值的算法,具体可以查看adaptiveThresholdTypes给出的具体内容,简要内容如下:



其中ADAPTIVE_THRESH_MEAN_C方法的阈值时由blockSize确定的像素(x, y)在blockSize x blockSize范围内的邻域像素值减参数C得到的平均值,而ADAPTIVE_THRESH_GAUSSIAN_C中阈值是blockSize x blockSize领域范围内减去C后的加权和。默认的sigma用于指定的blockSize,可通过getGaussianKernel查看详细信息。

. int thresholdType: 阈值类型,其取值有两种类型分别是:

(1).THRESH_BINARY,其数学模型公式如下所示:



(2).THRESH_BINARY_INV,其数学公式如下:



. int blockSize: 用于计算阈值大小的像素邻域尺寸,取值为3\5\7……

. double C: 自适应阈值算法中减去的常数值,通常是正数,在极少情况下式0或负值。

示例程序:

#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

using namespace std;
using namespace cv;

//定义全局变量
Mat srcImage, grayImage, dstImage;

const int thresholdTypeMaxValue = 1;
int thresholdTypeValue = 0;
const int CMaxValue = 50;
int CValue = 10;
const double maxValue = 255;
int blockSize = 5;

//定义回调函数
void adaptiveThresholdFun(int, void*);

int main()
{
Mat srcImage = imread("lena.jpg");

//判断图像是否读取成功
if(srcImage.empty())
{
cout << "图像读取失败!" << endl;
return -1;
}
else
cout << "图像读取成功!" << endl << endl;

cvtColor(srcImage, grayImage, COLOR_RGB2GRAY);
namedWindow("灰度图",WINDOW_AUTOSIZE);
imshow("灰度图", grayImage);

//轨迹条属性和依附窗口设置
namedWindow("二值图像", WINDOW_AUTOSIZE);
char thresholdTypeName[20];
sprintf(thresholdTypeName, "阈值类型\n 0: THRESH_BINARY\n 1: THRESH_BINARY_INV ", thresholdTypeMaxValue);
createTrackbar(thresholdTypeName, "二值图像", &thresholdTypeValue, thresholdTypeMaxValue, adaptiveThresholdFun);
adaptiveThresholdFun(thresholdTypeValue, 0);

char CName[20];
sprintf(CName, "常  数 %d", CMaxValue);
createTrackbar(CName, "二值图像", &CValue, CMaxValue, adaptiveThresholdFun);
adaptiveThresholdFun(CValue, 0);

waitKey(0);
return 0;
}

void adaptiveThresholdFun(int, void*)
{
int thresholdType;
switch(thresholdTypeValue)
{
case 0:
thresholdType = THRESH_BINARY;
break;

case 1:
thresholdType = THRESH_BINARY_INV;
break;

default:
break;
}
adaptiveThreshold(grayImage, dstImage, maxValue, ADAPTIVE_THRESH_MEAN_C,
thresholdType, blockSize, CValue);

imshow("二值图像", dstImage);
}


程序运行结果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息