OpenCV中有两个函数可以实现图片的二值化:
(1)cvThreshold( dst, dst,230 , 255, CV_THRESH_BINARY_INV)
(2)cvAdaptiveThreshold( dst, dst, 255, CV_ADAPTIVE_THRESH_MEAN_C,CV_THRESH_BINARY, 9, -10)
方法(1)是手动指定一个阈值,以此阈值御烂缓来进行二值化处理。其中的第四个参数决定了该方法的结果:
threshold_type=CV_THRESH_BINARY:
dst(x,y) = max_value, if src(x,y)>threshold 0, otherwise.
threshold_type=CV_THRESH_BINARY_INV:
dst(x,y) = 0, if src(x,y)>thresholddst(x,y) = max_value, otherwise.
threshold_type=CV_THRESH_TRUNC:
dst(x,y) = threshold, if src(x,y)>thresholddst(x,y) = src(x,y), otherwise.
threshold_type=CV_THRESH_TOZERO:
dst(x,y) = src(x,y), if (x,y)>threshold dst(x,y) = 0, otherwise.
threshold_type=CV_THRESH_TOZERO_INV:
dst(x,y) = 0, if src(x,y)>threshold dst(x,y) = src(x,y), otherwise.
值得一说的是threshold_type可以使用CV_THRESH_OTSU类型,这样该函数镇模就会使用大律法OTSU得到的全局自适应阈值来进行二值化图片,而参数中的threshold不再起 作用。比如:cvThreshold( dst, dst,300 , 255, CV_THRESH_OTSU | CV_THRESH_BINARY_INV)这种方法对于灰度直方图呈现二峰特征的图片处理历棚起来效果很好。
方法(2)是一个自适应阈值二值化方法,通过设定最后两个参数来调整效果。
//将标记处改成如下即可:#include "stdafx.h"
//液桥#include "stdafx.h"闹贺猛
#include <cv.h>
#include <highgui.h>
#include <cxcore.h>
using namespace cv
int main(int argc,char** argv)
{
IplImage *src=cvLoadImage("D:\\Lena.jpg",0)
if(src==NULL)
{
return 0
}
cvNamedWindow("src", CV_WINDOW_AUTOSIZE)
cvShowImage("src", src)
IplImage *dst1_img=cvCreateImage(cvGetSize(src),IPL_DEPTH_8U,1)
cvSmooth (src, dst1_img, CV_GAUSSIAN, 11, 0, 0, 0)
cvNamedWindow ("Gaussian", CV_WINDOW_AUTOSIZE)
cvShowImage ("Gaussian", dst1_img)
IplImage *adaptive_img = cvCreateImage(cvGetSize(dst1_img),IPL_DEPTH_8U,1)
cvAdaptiveThreshold(dst1_img, adaptive_img, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 7, 8)//函数改成这样即可拍嫌
cvNamedWindow ("adaptive", CV_WINDOW_AUTOSIZE)
cvShowImage ("adaptive", adaptive_img)
waitKey()
return 0
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)