如何用openCV检测图像中的圆圈?

时间:2013-10-26 16:35:17

标签: c opencv

我想检测图片中的圆圈。这是我尝试检测此图片中圈数的代码:enter image description here

 #include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <stdio.h>

/** @function main */
int main(int argc, char** argv)
{
  //load image from directory
    IplImage* gray = cvLoadImage("comb.png",0);


   // IplImage* gray = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1);
    CvMemStorage* storage = cvCreateMemStorage(0);

    //covert to grayscale
    cvCvtColor(gray, gray, CV_RGB2GRAY);

    // This is done so as to prevent a lot of false circles from being detected
   cvSmooth(gray, gray, CV_GAUSSIAN, 7, 7);

   IplImage* canny = cvCreateImage(cvGetSize(gray),IPL_DEPTH_8U,1);
    //IplImage* rgbcanny = cvCreateImage(cvGetSize(gray),IPL_DEPTH_8U,3);
  cvCanny(gray, canny, 10, 20, 3);

    //detect circles
    CvSeq* circles = cvHoughCircles(gray, storage, CV_HOUGH_GRADIENT, 1, gray->width/10);

    if(circles->total>0)
    printf("circles found: %d\n",circles->total);
    else
    printf("circles not found");


  return 0;
}

但发生以下错误: - OpenCV错误:cvCvtColor中的断言失败(dst.data == dst0.data),文件/OpenCV/OpenCV-2.4.3/modules/imgproc/src/color.cpp,第3811行 在抛出'cv :: Exception'的实例后终止调用   what():/ OpenCV/OpenCV-2.4.3/modules/imgproc/src/color.cpp:3811:错误:(-215)dst.data == dst0.data in function cvCvtColor

请告诉我程序有什么问题。我正在使用ubuntu linux。

1 个答案:

答案 0 :(得分:0)

您将gray打开为灰色图像(cvLoadImage("comb.png",0),其中“0”表示“灰度”)。然后你尝试将这个灰色的帧从RGB转换为灰色,当然这不起作用,因为你的图像已经是灰色的。

只需尝试注释以下行:

//covert to grayscale
cvCvtColor(gray, gray, CV_RGB2GRAY);

顺便说一下,你应该使用

IplImage* gray = cvLoadImage("comb.png", CV_LOAD_IMAGE_GRAYSCALE);

而不是

IplImage* gray = cvLoadImage("comb.png", 0);

更清楚。