首页 文章

OpenCV:blob周围的轮廓不正确

提问于
浏览
2

我试图在二进制图像中绘制斑点周围的轮廓,但是,有时,openCV围绕两个不同的斑点绘制单个轮廓 . 下面是一个例子 . 我该如何解决这个问题?
alt text

在这里它应该为右边的blob绘制两个边界框,并为左边的一个绘制 . 我同意他们很近但距离足够远 . 我只绘制外部轮廓而不是树或列表 . 我也使用cvFindNextContour(contourscanner),因为这对我的案例来说更容易实现 .

谢谢

编辑:“输出”窗口中显示的图像来自不同的功能,只执行图像减法 . “轮廓”窗口中显示的图像位于pplfind()函数中 . “输出”图像传递给img_con() .

IplImage* img_con(IplImage* image){
    int ppl;
    CvMemStorage* memstr = cvCreateMemStorage();
    IplImage* edges = cvCreateImage(cvGetSize(image),8,1);
    cvCanny(image,edges,130,255);
    CvContourScanner cscan = cvStartFindContours(image,memstr,sizeof(CvContour),CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE,cvPoint(0,0)); 

 ppl = pplfind(cscan,cvGetSize(image));
if (ppl !=0 )
    printf("Estimated number of people: %d\n",ppl);
cvEndFindContours(&cscan);
cvClearMemStorage(memstr);

return edges;
 

 } 

 int pplfind(CvContourScanner cscan, CvSize frSize){
    ofstream file; char buff[50];
    file.open("box.txt",ofstream::app);
    int ppl =0;
    CvSeq* c;
    IplImage *out = cvCreateImage(frSize,8,3);
    while (c = cvFindNextContour(cscan)){
        CvRect box = cvBoundingRect(c,1);
        if ((box.height > int(box.width*1.2))&&(box.height>20)){//&&(box.width<20)){//
            ppl++;
            cvRectangle(out,cvPoint(box.x,box.y),cvPoint(box.x+box.width,box.y+box.height),CV_RGB(255,0,50),1); 

         cvShowImage("contours",out);
        //cvWaitKey();
    }
    //printf("Box Height: %d , Box Width: %d ,People: %d\n",box.height,box.width,ppl);
    //cvWaitKey(0);
    int coord = sprintf_s(buff,"%d,%d,%d\n",box.width,box.height,ppl);
    file.write(buff,coord);
}
file.close();
cvReleaseImage(&out);
return ppl;
 

 }

1 回答

  • 2

    我从未使用 cvFindNextContour ,但在图像上运行 cvFindContours 并使用 CV_RETR_EXTERNAL 似乎工作正常:

    alt text

    我使用的是OpenCV Python,所以这段代码可能对你没用,但为了完整起见,这里有:

    contours = cv.FindContours(img, cv.CreateMemStorage(0), mode=cv.CV_RETR_EXTERNAL)
    while contours:
        (x,y,w,h) = cv.BoundingRect(contours)
        cv.Rectangle(colorImg, (x,y), (x+w,y+h), cv.Scalar(0,255,255,255))
        contours = contours.h_next()
    

    编辑:您询问如何仅绘制具有某些属性的轮廓;它会是这样的:

    contours = cv.FindContours(img, cv.CreateMemStorage(0), mode=cv.CV_RETR_EXTERNAL)
    while contours:
        (x,y,w,h) = cv.BoundingRect(contours)
        if h > w*1.2 and h > 20:
            cv.Rectangle(colorImg, (x,y), (x+w,y+h), cv.Scalar(0,255,255,255))
        contours = contours.h_next()
    

相关问题