这里主要讲下通过 Sobel算子、Laplace算子、Canny算子来实现图像的边缘检测,先来看下Sobel算子的实现:
#include<cv.h> #include<highgui.h> int main() { IplImage* pImage = NULL; IplImage* pImgSobelgray = NULL; IplImage* pImg8u = NULL; IplImage* pImg8uSmooth = NULL; IplImage* pImgColor = NULL; IplImage* pImgSobelcolor = NULL; IplImage* pImgPlanes[3] = {0,0,0}; pImage = cvLoadImage ("1.jpg", 1); cvNamedWindow ("src", 1); cvShowImage ("src", pImage); /*灰度图的处理*/ pImg8u = cvCreateImage (cvGetSize(pImage), IPL_DEPTH_8U, 1); pImg8uSmooth = cvCreateImage (cvGetSize(pImage), IPL_DEPTH_8U, 1); cvCvtColor (pImage, pImg8u, CV_BGR2GRAY); cvSmooth (pImg8u, pImg8uSmooth, CV_GAUSSIAN, 3, 0, 0); pImgSobelgray = cvCreateImage (cvGetSize(pImage), IPL_DEPTH_16S, 1); cvSobel (pImg8uSmooth, pImgSobelgray, 0, 1, 3); cvConvertScaleAbs (pImgSobelgray, pImg8u, 1, 0); cvNamedWindow ("Sobel gray Image", 1); cvShowImage ("Sobel gray Image", pImg8u); /*彩色图的处理*/ int i; for (i = 0; i < 3; i++) { pImgPlanes[i] = cvCreateImage (cvSize(pImage->width, pImage->height), 8, 1); } pImgSobelcolor = cvCreateImage (cvSize(pImage->width, pImage->height), IPL_DEPTH_16S, 1); pImgColor = cvCreateImage (cvSize(pImage->width, pImage->height), 8, 3); cvCvtPixToPlane (pImage, pImgPlanes[0], pImgPlanes[1], pImgPlanes[2], NULL); for (i = 0; i < 3; i++) { cvSobel (pImgPlanes[i], pImgSobelcolor, 0, 1, 3); cvConvertScaleAbs (pImgSobelcolor, pImgPlanes[i], 1, 0); } cvCvtPlaneToPix (pImgPlanes[0], pImgPlanes[1], pImgPlanes[2], NULL, pImgColor); cvNamedWindow ("Sobel color Image", 1); cvShowImage ("Sobel color Image", pImgColor); cvWaitKey (0); cvReleaseImage (&pImage); cvReleaseImage (&pImgSobelgray); cvReleaseImage (&pImgSobelcolor); cvReleaseImage (&pImg8u); cvReleaseImage (&pImg8uSmooth); cvReleaseImage (&pImgColor); return 0; }
对于利用Laplace算子实现边缘检测可以说和Sobel是一模一样的,这里就不再给出代码啦!
下面看下最后一个代码,即Canny算子实现边缘检测,其实基本也和前面是一样的,唯一的区别在于转换时的目标图像。对于前两个来说,当输入图像是8位时,要求输出图像是16位,但Canny则不需要。看Canny的代码:
#include<cv.h> #include<highgui.h> int main() { IplImage* pImage = NULL; IplImage* pImgCanny = NULL; IplImage* pImg8u = NULL; IplImage* pImg8uSmooth = NULL; pImage = cvLoadImage ("1.jpg", 1); cvNamedWindow ("src", 1); cvShowImage ("src", pImage); pImg8u = cvCreateImage (cvGetSize(pImage), IPL_DEPTH_8U, 1); pImg8uSmooth = cvCreateImage (cvGetSize(pImage), IPL_DEPTH_8U, 1); pImgCanny = cvCreateImage (cvGetSize(pImage), IPL_DEPTH_8U, 1); cvCvtColor (pImage, pImg8u, CV_BGR2GRAY); cvSmooth (pImg8u, pImg8uSmooth, CV_GAUSSIAN, 3, 0, 0); cvCanny (pImg8uSmooth, pImgCanny, 100, 200, 3); cvConvertScaleAbs (pImgCanny, pImg8u, 1, 0); cvNamedWindow ("Canny Image", 1); cvShowImage ("Canny Image", pImg8u); cvWaitKey (0); cvReleaseImage (&pImage); cvReleaseImage (&pImgCanny); cvReleaseImage (&pImg8u); cvReleaseImage (&pImg8uSmooth); return 0; }