在opencv中识别检测到的圆圈的颜色

时间:2011-10-18 00:35:50

标签: colors opencv geometry

如何使用opencv中的cvHoughcircles来识别每个检测到的圆圈的颜色? 我添加了代码,显示我当前正在尝试但我收到错误:imageTest1.exe中的0x758d9617处理未处理的异常:Microsoft C ++异常:cv ::内存位置的异常0x0019eed4

#include <stdio.h>
#include <cv.h>
#include <highgui.h>
#include <math.h>

int main(int argc, char** argv)
{
    //load image from directory
    IplImage* img = cvLoadImage("C:\\Users\\Nathan\\Desktop\\SnookerPic.png");


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

    //covert to grayscale
    cvCvtColor(img, gray, CV_BGR2GRAY);

    // 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(img),IPL_DEPTH_8U,1);
    IplImage* rgbcanny = cvCreateImage(cvGetSize(img),IPL_DEPTH_8U,3);
    cvCanny(gray, canny, 50, 100, 3);

    //detect circles
    CvSeq* circles = cvHoughCircles(gray, storage, CV_HOUGH_GRADIENT, 1, 35.0, 75, 60,0,0);
    cvCvtColor(canny, rgbcanny, CV_GRAY2BGR);

    //draw all detected circles
    for (int i = 0; i < circles->total; i++)
    {
         // round the floats to an int
         float* p = (float*)cvGetSeqElem(circles, i);
         cv::Point center(cvRound(p[0]), cvRound(p[1]));
         int radius = cvRound(p[2]);
cvScalar c;
         c = cvGet2D(img, center.x, center.y);//colour of circle

         // draw the circle center
         cvCircle(img, center, 3, CV_RGB(0,255,0), -1, 8, 0 );

         // draw the circle outline
         cvCircle(img, center, radius+1, CV_RGB(0,0,255), 2, 8, 0 );

         //display coordinates
         printf("x: %d y: %d r: %d\n",center.x,center.y, radius);
    }

    //create window
    cvNamedWindow("circles", 1);
    cvNamedWindow("SnookerImage", 1);
    //show image in window
    cvShowImage("circles", rgbcanny);
    cvShowImage("SnookerImage", img);

    cvSaveImage("out.png", rgbcanny);
    cvWaitKey(0);

    return 0;
}

1 个答案:

答案 0 :(得分:2)

看起来您尝试获取颜色的当前圆圈的坐标超出范围。您应该检查每个点是否在图像范围内(例如center.x&gt; 0&amp;&amp; center.x&lt; image.width&amp;&amp; center.y&gt; 0&amp;&amp; center.y&lt; image.height)在尝试获取颜色之前。