标签:
图像的二值化:
与边缘检测相比,轮廓检测有时能更好的反映图像的内容。而要对图像进行轮廓检测,则必须要先对图像进行二值化,图像的二值化就是将图像上的像素点的灰度值设置为0或255,这样将使整个图像呈现出明显的黑白效果。在数字图像处理中,二值图像占有非常重要的地位,图像的二值化使图像中数据量大为减少,从而能凸显出目标的轮廓。
下面就介绍OpenCV中对图像进行二值化的关键函数——cvThreshold()。
函数功能:采用Canny方法对图像进行边缘检测
函数原型:
void cvThreshold(
const CvArr* src, 第一个参数表示输入图像,必须为单通道灰度图。
CvArr* dst, 第二个参数表示输出的边缘图像,为单通道黑白图。
double threshold, 第三个参数表示阈值
double max_value, 第四个参数表示最大值
int threshold_type 第五个参数表示运算方法。
);
在OpenCV的imgproc\types_c.h中可以找到运算方法的定义。
enum
{
CV_THRESH_BINARY =0, value = value > threshold ? max_value : 0
CV_THRESH_BINARY_INV =1, value = value > threshold ? 0 : max_value
CV_THRESH_TRUNC =2, value = value > threshold ? threshold : value
CV_THRESH_TOZERO =3, value = value > threshold ? value : 0
CV_THRESH_TOZERO_INV =4, value = value > threshold ? 0 : value
CV_THRESH_MASK =7,
CV_THRESH_OTSU =8 use Otsu algorithm to choose the optimal threshold value;
combine the flag with one of the above CV_THRESH_* values
};
#include "stdafx.h" #include "iostream" using namespace std; #include "opencv2/opencv.hpp" IplImage *pGrayImage = NULL; IplImage *pBinaryImage = NULL; const char *pImagePath = "E:/C_VC_code/Text_Photo/girl001.jpg"; const char *pGrayWindowsTitle = "原图"; const char *pBinaryWindowsTitle = "二值图"; const char *pWindowsToolBarTitle = "阀值"; void onCallBack(int pos) { //change into binary image cvThreshold(pGrayImage, pBinaryImage, pos, 255, CV_THRESH_BINARY); cvShowImage(pBinaryWindowsTitle,pBinaryImage); } int main() { //load srcouse image from file //IplImage *pImage = cvLoadImage(pImagePath, CV_LOAD_IMAGE_UNCHANGED); //load gray image from srcouce file image pGrayImage = cvLoadImage(pImagePath, CV_LOAD_IMAGE_GRAYSCALE); //cvCvtColor(pImage,pGrayImage,CV_BGR2GRAY); pBinaryImage = cvCreateImage(cvGetSize(pGrayImage), IPL_DEPTH_8U,1); //create window and show orial image cvNamedWindow(pGrayWindowsTitle,CV_WINDOW_AUTOSIZE); cvNamedWindow(pBinaryWindowsTitle,CV_WINDOW_AUTOSIZE); //creat slide bar int pos = 1; cvCreateTrackbar(pWindowsToolBarTitle, pBinaryWindowsTitle, &pos, 100,onCallBack); onCallBack(0); cvShowImage(pGrayWindowsTitle,pGrayImage); cvShowImage(pBinaryWindowsTitle,pBinaryImage); cvWaitKey(0); cvDestroyWindow(pBinaryWindowsTitle); cvDestroyWindow(pGrayWindowsTitle); cvReleaseImage(&pGrayImage); cvReleaseImage(&pBinaryImage); return 0; }
标签:
原文地址:http://www.cnblogs.com/mypsq/p/4983585.html