OpenCv超出范围错误

时间:2011-10-22 02:01:20

标签: opencv range

我正在检测图像中的圆圈。我试图读取这些圆圈的中心的像素值,以获得它们的颜色。我正在使用cvPtr2D(img, center.x, center.y, NULL);来读取for循环中每个圆的值但是我得到一个错误,“其中一个参数'值超出范围(索引超出范围),在inknown函数中,第179行(这是cvPtr2D()的一行。我不明白这些值是如何超出范围的。任何人都可以提供帮助吗?发布我的代码

#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]);
         uchar* ptr;
         ptr = cvPtr2D(img, center.x, center.y, NULL);
         printf("B: %d G: %d R: %d\n", ptr[0],ptr[1],ptr[2]);
         //CvScalar c;
         //if(center.x > 0 && center.x < 1280 && center.y > 0 && center.y < 720)
         //{
         //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", img);
    //cvDestroyWindow("SnookerImage");
    //cvDestroyWindow("circles");
    //cvReleaseMemStorage("storage");
    cvWaitKey(0);

    return 0;
}

enter image description here

1 个答案:

答案 0 :(得分:1)

你的问题在于:

ptr = cvPtr2D(img, center.x, center.y, NULL);

应该是:

ptr = cvPtr2D(img, center.y, center.x, NULL);

不幸的是,文档对此并不十分清楚。我的直觉告诉我,这就是发生的事情,但我不得不实际上使用OpenCV源代码来查看它是如何用于确认的。

你的例子现在看起来正在运作。