cvThreshold()函數以下:函數
double cvThreshold(CvArr* src, CvArr* dst, double threshold, double max_value, int threshold_type);
cvShold函數只能處理8位或者浮點灰度圖像,目標圖像必須與源圖像一致,或者爲8爲圖像 。ui
實現閾值化的代碼以下:spa
#include <cv.h> #include <highgui.h> #pragma comment(lib, "ml.lib") #pragma comment(lib, "cv.lib") #pragma comment(lib, "cvaux.lib") #pragma comment(lib, "cvcam.lib") #pragma comment(lib, "cxcore.lib") #pragma comment(lib, "cxts.lib") #pragma comment(lib, "highgui.lib") #pragma comment(lib, "cvhaartraining.lib") int main() { IplImage* sourceImage; IplImage* dstImage; if(!(sourceImage = cvLoadImage("D:\\Testing_Images\\view.png"))) 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; }
在自適應閾值中,閾值自己就是一個變量,實現自適應閾值的代碼以下:code
#include <cv.h> #include <highgui.h> #pragma comment(lib, "ml.lib") #pragma comment(lib, "cv.lib") #pragma comment(lib, "cvaux.lib") #pragma comment(lib, "cvcam.lib") #pragma comment(lib, "cxcore.lib") #pragma comment(lib, "cxts.lib") #pragma comment(lib, "highgui.lib") #pragma comment(lib, "cvhaartraining.lib") int main() { IplImage* sourceImage; //直接以灰度圖像載入 if(!(sourceImage = cvLoadImage("D:\\Testing_Images\\view.png", 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; }