OpenCV框架中提供了自适应阈值的范例:http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#adaptivethreshold
函数原型如下:
void adaptiveThreshold(InputArray src, OutputArray dst,
double maxValue, int adaptiveMethod,
int thresholdType, int blockSize, double C);
前两个参数分别是输入图像和保存输出阈值图像的位置。
maxValue
是通过条件判断后赋值给输出像素的阈值,
adaptiveMethod
是自适应阈值化使用的方法,
thresholdType
是要执行的阈值化类型(稍后会讲到),
blockSize
是要检查的窗口的大小(稍后会讲到),
C
是从每个窗口中减去的常数。我从未真正需要使用它,通常将其设置为0。
adaptiveThreshold
的默认方法是分析
blockSize x blockSize
窗口并计算该窗口内的平均强度减去
C
。如果此窗口的中心在平均强度之上,则将输出位置的相应位置设置为
maxValue
,否则同一位置将设置为 0。这应该解决了非均匀照明问题,而不是对整个图像应用全局阈值,而是在本地像素邻域上进行阈值化。
您可以阅读其他参数方法的文档,但是为了入门,您可以像这样做:
#include <cv.h>
#include <highgui.h>
using namespace cv;
void threshold()
{
Mat image;
image = imread("image.jpg", 1);
Mat gray_image;
cvtColor(image, gray_image, CV_BGR2GRAY);
namedWindow("Gray image", CV_WINDOW_AUTOSIZE);
imshow("Gray image", gray_image);
waitKey(0);
int maxValue = 255;
int blockSize = 25;
int C = 0;
adaptiveThreshold(gray_image, gray_image, maxValue,
CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY,
blockSize, C);
namedWindow("Thresholded image", CV_WINDOW_AUTOSIZE);
imshow("Thresholded image", gray_image);
waitKey(0);
}
int main( int argc, const char** argv )
{
threshold();
}