测试图片:
code:
#include <opencv\cv.h> #include <opencv\highgui.h> #include <opencv\cxcore.h> #include <stdlib.h> #include <stdio.h> int main(){ IplImage* src = NULL; src = cvLoadImage("C:\\Users\\zxl\\Desktop\\1.png", 1); if (!src){ return -1; } IplImage* pImgGray = cvCreateImage(cvGetSize(src), 8, 1); cvCvtColor(src, pImgGray, CV_BGR2GRAY); cvThreshold(pImgGray, pImgGray, 80, 255, CV_THRESH_BINARY_INV); IplConvKernel* element1 = cvCreateStructuringElementEx(3,1,1,0,CV_SHAPE_RECT,0); cvErode(pImgGray, pImgGray, element1, 1); cvDilate(pImgGray, pImgGray, element1, 1); IplConvKernel* element2 = cvCreateStructuringElementEx(1,3,0,1,CV_SHAPE_RECT,0); cvDilate(pImgGray, pImgGray, element2, 1); CvMemStorage* storage = cvCreateMemStorage(0); CvSeq* contour = NULL; IplImage* pImgEdge = cvCloneImage(pImgGray); int count = cvFindContours(pImgEdge, storage, &contour, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0)); int num = 0; for (; contour; contour = contour->h_next){ CvRect rect = cvBoundingRect(contour, 0); if ((rect.x > 30) && (rect.x+rect.width+30 < src->width) && (rect.y > 30) && (rect.y+rect.height+60 < src->height)){ //原始图像左右两侧一段可忽略,图像下面由于写入了ww......com这里也忽略 cvDrawContours(src, contour, CV_RGB(255,0,0), CV_RGB(255,0,0),0, 1, 8, cvPoint(0,0)); num++; } } //printf("count=%d,num=%d\n", count, num); cvNamedWindow("imgSrc", 1); cvNamedWindow("imgGray", 1); cvShowImage("imgSrc", src); cvShowImage("imgGray", pImgGray); cvWaitKey(0); //cvSaveImage("contour.jpg", src); //cvSaveImage("binary.jpg", pImgGray); cvReleaseImage(&pImgEdge); cvReleaseStructuringElement(&element2); cvReleaseStructuringElement(&element1); cvDestroyAllWindows(); cvReleaseImage(&pImgGray); cvReleaseImage(&src); return 0; }