cvFindContours始终返回1

时间:2013-09-27 15:54:16

标签: opencv

我正在使用OpenCV 2.4.6和Visual C ++ 2010.我试图在下面的代码中跟踪RED颜色。我正在使用cvInRangeS从图像中获取RED对象,该图像是二进制图像。然后使用cvFindContours(..)我想找到对象的轮廓。但是cvFindcontours(..)总是返回1.我也使用cvBoundingRect(..)来获取轮廓在图像中的位置。我得到的矩形位置总是(1,1,638,478)。表示cvFindcontour(..)将整个图像作为单个轮廓。如何才能获得轮廓中的RED对象?

int main()
{
IplImage*   mCVImageColor = cvCreateImageHeader(cvSize(640,480), IPL_DEPTH_8U, 3);
IplImage* imgTracking;

CvCapture* capture = cvCaptureFromCAM( CV_CAP_ANY );
namedWindow( "Display image", CV_WINDOW_AUTOSIZE );
namedWindow( "Display window", CV_WINDOW_AUTOSIZE );
namedWindow( "Display tracking", CV_WINDOW_AUTOSIZE );
namedWindow( "Display thresh", CV_WINDOW_AUTOSIZE );
CvRect rect;
CvMemStorage *storage = cvCreateMemStorage(0);
CvSeq *contours=0;
while(1)
{
    IplImage* mCVImageColor = cvQueryFrame( capture );
    cvSmooth(mCVImageColor, mCVImageColor, CV_GAUSSIAN,3,3); 
    imgTracking=cvCreateImage(cvGetSize(mCVImageColor),IPL_DEPTH_8U, 1);

    IplImage* imgHSV = cvCreateImage(cvGetSize(mCVImageColor), IPL_DEPTH_8U, 3); 
    IplImage* imgThresh=cvCreateImage(cvGetSize(mCVImageColor),8, 1);
    cvCvtColor(mCVImageColor, imgHSV, CV_BGR2HSV);

    cvInRangeS(imgHSV, cvScalar(170,160,60), cvScalar(180,255,256), imgThresh); 

    cvAdd(imgThresh, imgTracking, imgTracking);
    cvConvertScale(imgTracking, imgTracking, 1.0, 0.0);
    int x = cvFindContours(imgTracking,storage,&contours,sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(2, 2));
    printf("%d\n",contours->total);
    for (; contours != 0; contours = contours->h_next)
    {
        rect = cvBoundingRect(contours); //extract bounding box for current contour
        //drawing rectangle
        cvRectangle(mCVImageColor,cvPoint(rect.x, rect.y),cvPoint(rect.x+rect.width, rect.y+rect.height),cvScalar(0, 0, 255),2, 8, 0);  
        printf("%d   %d  %d  %d\n",rect.x, rect.y,rect.width,rect.height);
        if(rect.width*rect.height<1400)
        {
            CvPoint centroid[1];
            centroid[0].x = cvRound((rect.x+rect.width)/2);
            centroid[0].y = cvRound((rect.y+rect.height)/2);
            cvCircle( mCVImageColor, centroid[0], 5, CV_RGB(255, 0, 0),10, -1);
        }
    }
    cvShowImage("Display tracking",imgTracking);
    cvShowImage("Display window",imgHSV);
    cvShowImage("Display image",mCVImageColor);
    cvShowImage("Display thresh",imgThresh);
    cvClearMemStorage( storage );
    contours = 0;
    //cvReleaseImage(&imgHSV);
    //cvReleaseImage(&imgThresh);  
    int c = waitKey(20);
    if(c=='q')
        break;
}

}

0 个答案:

没有答案