Opencv中提供了很多關於圖像輪廓處理的函數,這裡我用cvFindContours函數來提取輪廓,並用cvDrawContours函數將提取的輪廓畫出來。函數cvFindContours的第一個參數就是我們要進行提取輪廓的目標圖像,這裡要注意,這個圖像必須是一個二值圖。得到二值圖的方法有很多,這裡我采用的是cvThreshold函數,通過設置閥值來得到相應的二值圖。當然,這裡閥值的選擇根據不同的圖像可以自己適當的調整,這樣效果就比較好了!
下面是源碼:
#include<cv.h>
#include<highgui.h>
int main()
{
IplImage* src = NULL;
IplImage* img = NULL;
IplImage* dst = NULL;
CvMemStorage* storage = cvCreateMemStorage (0);;
CvSeq* contour = 0;
int contours = 0;
CvScalar external_color;
CvScalar hole_color;
src = cvLoadImage ("test.jpg", 1);
img = cvCreateImage (cvGetSize(src), IPL_DEPTH_8U, 1);
dst = cvCreateImage (cvGetSize(src), src->depth, src->nChannels);
cvCvtColor (src, img, CV_BGR2GRAY);
cvThreshold (img, img, 100, 200, CV_THRESH_BINARY);
contours = cvFindContours (img, storage, &contour, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
for (;contour != 0; contour = contour->h_next)
{
external_color = CV_RGB(rand()&255, rand()&255, rand()&255);
hole_color = CV_RGB(rand()&255, rand()&255, rand()&255);
cvDrawContours (dst, contour, external_color, hole_color, 1, 2, 8);
}
cvNamedWindow ("Contour", 1);
cvShowImage ("Contour", dst);
cvWaitKey (0);
cvReleaseMemStorage (&storage);
cvReleaseImage (&src);
cvReleaseImage (&img);
cvReleaseImage (&dst);
return 0;
}
源圖: 運行結果圖:
Objective-C中@property的所有屬性詳解 http://www.linuxidc.com/Linux/2014-03/97744.htm
Objective-C 和 Core Foundation 對象相互轉換的內存管理總結 http://www.linuxidc.com/Linux/2014-03/97626.htm
使用 Objective-C 一年後我對它的看法 http://www.linuxidc.com/Linux/2013-12/94309.htm
10個Objective-C基礎面試題,iOS面試必備 http://www.linuxidc.com/Linux/2013-07/87393.htm
Objective-C適用C數學函數 <math.h> http://www.linuxidc.com/Linux/2013-06/86215.htm