AdaptiveThreshold
自适应阈值方法
void cvAdaptiveThreshold( const CvArr* src, CvArr* dst, double max_value,
int adaptive_method=CV_ADAPTIVE_THRESH_MEAN_C,
int threshold_type=CV_THRESH_BINARY,
int block_size=3, double param1=5 );
src
输入图像.
dst
输出图像.
max_value
使用 CV_THRESH_BINARY 和 CV_THRESH_BINARY_INV 的最大值.
adaptive_method
自适应阈值算法使用:CV_ADAPTIVE_THRESH_MEAN_C 或 CV_ADAPTIVE_THRESH_GAUSSIAN_C (见讨论).
threshold_type
取阈值类型:必须是下者之一
CV_THRESH_BINARY,
CV_THRESH_BINARY_INV
block_size
用来计算阈值的象素邻域大小: 3, 5, 7, ...
param1
与方法有关的参数。对方法 CV_ADAPTIVE_THRESH_MEAN_C 和 CV_ADAPTIVE_THRESH_GAUSSIAN_C, 它是一个从均值或加权均值提取的常数(见讨论), 尽管它可以是负数。
函数 cvAdaptiveThreshold 将灰度图像变换到二值图像,采用下面公式:
threshold_type=CV_THRESH_BINARY:
dst(x,y) = max_value, if src(x,y)>T(x,y)
0, otherwise
threshold_type=CV_THRESH_BINARY_INV:
dst(x,y) = 0, if src(x,y)>T(x,y)
max_value, otherwise
其中 TI 是为每一个象素点单独计算的阈值
对方法 CV_ADAPTIVE_THRESH_MEAN_C,先求出块中的均值,再减掉param1。
对方法 CV_ADAPTIVE_THRESH_GAUSSIAN_C ,先求出块中的加权和(gaussian), 再减掉param1。
例子:
/************cvAdaptiveThreshold Example************/ #include "highgui.h" #include "cv.h" #include <stdlib.h> #include <stdio.h> char wnd1[] = "in"; char wnd2[] = "out"; //读取trackbar上的两个值,实际两参数计算在on_track里 int _blocksize = 0; int _param1 = 0; IplImage *pImg = NULL; //源图像 IplImage *pGray = NULL; //灰度图 IplImage *pOut = NULL; //二值图 void on_track(int position); //trackbar回调函数
int main(int argc, char **argv) { cvNamedWindow(wnd1, 1); cvNamedWindow(wnd2, 1); pImg = cvLoadImage(argv[1]); pGray = cvCreateImage(cvGetSize(pImg), IPL_DEPTH_8U, 1); pOut = cvCreateImage(cvGetSize(pImg), IPL_DEPTH_8U, 1); cvCvtColor(pImg, pGray, CV_RGB2GRAY); //创建两个滑动条 cvCreateTrackbar("blocksize", wnd2, &_blocksize, 50, on_track); cvCreateTrackbar("param1", wnd2, &_param1, 100, on_track); cvShowImage(wnd1, pImg); cvWaitKey(0); cvReleaseImage(&pImg); cvReleaseImage(&pOut); cvReleaseImage(&pGray); cvDestroyWindow(wnd1); cvDestroyWindow(wnd2); return 0; } void on_track(int position) { int blocksize = _blocksize * 2 + 3; //计算阈值的像素邻域大小3,5,7... int param1 = _param1 - 50; //被均值和加权均值减去的常量, 范围取[-50,50] cvAdaptiveThreshold(pGray, pOut, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, blocksize, param1 ); printf("blocksize: %d, param1: %d\n", blocksize, param1); cvShowImage(wnd2, pOut); }
|