看代码:
IplImage *g = cvLoadImage("C:\\Users\\Administrator\\Desktop\\21.jpg"); IplImage* src = cvCreateImage(cvGetSize(g), IPL_DEPTH_8U, 1); //转化为单通道黑白照片 CvScalar pixel1; double temp; for (int i = 0; i < g->height - 1; ++i) { for (int j = 0; j < g->width - 1; ++j) { pixel1 = cvGet2D(g, i, j); temp = 0.11*pixel1.val[0] + 0.59*pixel1.val[1] + 0.30*pixel1.val[2]; cvSet2D(src, i, j, temp); } } CvMemStorage* storage = cvCreateMemStorage(0); CvSeq* contour = 0; cvNamedWindow("image0", 1); cvShowImage("image0", src); int hei = src->height; int wid = src->width; uchar *data = (uchar*)src->imageData; int widstep = src->widthStep; int channel = src->nChannels; IplImage *dst = cvCreateImage(cvSize(wid, hei), IPL_DEPTH_8U, 3); // invert the image for (int i = 0; i<hei; i++) { for (int j = 0; j<wid; j++) { if (data[i*widstep + j*channel]>160) { data[i*widstep + j*channel] = 255; } else { data[i*widstep + j*channel] = 0; } } } cvNamedWindow("image", 0); cvShowImage("image", src); printf("图像的高为:%d,宽为:%d\n\n", hei, wid); cvCvtColor(src, dst, CV_GRAY2BGR); cvFindContours(src, storage, &contour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); for (; contour != 0; contour = contour->h_next) { CvBox2D rect = cvMinAreaRect2(contour, storage); double area = rect.size.height* rect.size.width; if (area < 1000)continue; CvPoint2D32f rect_pts0[4]; cvBoxPoints(rect, rect_pts0); int npts = 4, k = 0; int aaa = 0, bbb = 0; CvPoint rect_pts[4], *pt = rect_pts; printf("连通区域最小外接矩形顶点坐标分别为:\n"); for (int i = 0; i<4; i++) { rect_pts[i] = cvPointFrom32f(rect_pts0[i]); printf("%d %d\n", rect_pts[i].x, rect_pts[i].y); aaa = (int)sqrt((pow((rect_pts[0].x - rect_pts[1].x), 2) + pow((rect_pts[0].y - rect_pts[1].y), 2))); bbb = (int)sqrt((pow((rect_pts[0].x - rect_pts[3].x), 2) + pow((rect_pts[0]. y - rect_pts[3].y), 2))); if (aaa<bbb) { k = aaa; aaa = bbb; bbb = k; } } printf("最小外接矩形的长为:%d宽为:%d。\n\n", aaa, bbb); cvPolyLine(g, &pt, &npts, 1, 1, CV_RGB(255, 0, 0), 1); } cvNamedWindow("image1", 1); cvShowImage("image1", g); cvNamedWindow("image", 1); cvShowImage("image", src); cvWaitKey(0); cvDestroyWindow("image"); cvDestroyWindow("image1"); cvReleaseImage(&src); cvReleaseImage(&g);