【学习opencv第七篇】图像的阈值化

图像阈值化的基本思想是,给定一个数组和一个阈值,然后根据数组中每个元素是低于还是高于阈值而进行一些处理。

cvThreshold()函数如下:

 

double cvThreshold(
	CvArr* src,  
	CvArr* dst,
	double threshold,     
	double max_value,    
	int threshold_type
	)

cvShold函数只能处理8位或者浮点灰度图像,目标图像必须与源图像一致,或者为8为图像

 

实现阈值化的代码如下:

 

#include "stdafx.h"
#include <highgui.h>
#include <math.h>
#include <cv.h>
using namespace std;
int main()
{
	IplImage* sourceImage;
	IplImage* dstImage;   
	if(!(sourceImage=cvLoadImage("Hough.jpg")))
		return -1;
	dstImage=cvCreateImage(cvGetSize(sourceImage),sourceImage->depth,1);

	IplImage* r=cvCreateImage(cvGetSize(sourceImage),IPL_DEPTH_8U,1);
	IplImage* g=cvCreateImage(cvGetSize(sourceImage),IPL_DEPTH_8U,1);
	IplImage* b=cvCreateImage(cvGetSize(sourceImage),IPL_DEPTH_8U,1);
	IplImage* tempImage=cvCreateImage(cvGetSize(sourceImage),IPL_DEPTH_8U,1);
	cvSplit(sourceImage,r,g,b,NULL);

	cvAddWeighted(r,1./3.,g,1./3.,0.0,tempImage);
	cvAddWeighted(tempImage,1,b,1./3.,0.0,tempImage);
	cvThreshold(tempImage,dstImage,100,255,CV_THRESH_BINARY);
	//对于大于100的设为255
	cvNamedWindow("sourceImage");
	cvNamedWindow("dstImage");
	cvShowImage("sourceImage",sourceImage);
	cvShowImage("dstImage",dstImage);

	cvWaitKey(-1);
	cvReleaseImage(&r);
	cvReleaseImage(&g);
	cvReleaseImage(&b);
	cvDestroyWindow("sourceImage");
	cvDestroyWindow("dstImage");

	cvReleaseImage(&sourceImage);
	cvReleaseImage(&dstImage);
	return 0;
}

运行结果:

 

【学习opencv第七篇】图像的阈值化_第1张图片

在自适应阈值中,阈值本身就是一个变量,实现自适应阈值的代码如下:


 

#include "stdafx.h"
#include <highgui.h>
#include <math.h>
#include <cv.h>
int main()
{
	IplImage* sourceImage;
	
	//直接以灰度图像载入
	if(!(sourceImage=cvLoadImage("Hough.jpg",CV_LOAD_IMAGE_GRAYSCALE)))
		return -1;
	IplImage* dstImage=cvCreateImage(cvGetSize(sourceImage),IPL_DEPTH_8U,1);
	
	//这个函数只能处理单通道图像或者8位图像,并且要求源图像	与目标图像不能为同一个图像
	cvAdaptiveThreshold(
		sourceImage,
		dstImage,
		255,     //max_val
		CV_ADAPTIVE_THRESH_MEAN_C,
		CV_THRESH_BINARY,
		3,      //block_size
		5       //offset
		);
	cvNamedWindow("AdaptiveThreshold",0);
	cvShowImage("AdaptiveThreshold",dstImage);
	
	//单一阈值
	IplImage* dstImage2=cvCreateImage(cvGetSize(sourceImage),IPL_DEPTH_8U,1);
	cvThreshold(sourceImage,dstImage2,100,255,CV_THRESH_BINARY);
	
	cvNamedWindow("sourceImage",0);
	cvNamedWindow("Threshold",0);
	cvShowImage("sourceImage",sourceImage);
	cvShowImage("Threshold",dstImage2);
	
	cvWaitKey(-1);
	
	//释放资源
	cvDestroyWindow("sourceImage");
	cvDestroyWindow("Threshold");
	cvDestroyWindow("AdaptiveThreshold");
	cvReleaseImage(&sourceImage);
	cvReleaseImage(&dstImage);
	cvReleaseImage(&dstImage2);
	return 0;
}

运行结果:

 

【学习opencv第七篇】图像的阈值化_第2张图片

Reference《学习opencv》

 

你可能感兴趣的:(opencv)