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;
}
源图: 运行结果图:
再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://www.cnblogs.com/captainbed
原文地址:https://www.cnblogs.com/sownchz/p/10174227.html
时间: 2024-10-05 01:59:46