在opencv中读取像素的HSV值

时间:2011-10-22 11:32:43

标签: opencv pixel hsv

你将如何读取HSV格式而不是RGB的像素值?下面的代码以RGB格式读取圆圈中心的像素值。在HSV阅读价值方面有很大差异吗?

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.y, center.x, NULL);
         //printf("B: %d G: %d R: %d\n", ptr[0],ptr[1],ptr[2]);
         CvScalar s;

         s = cvGet2D(img,center.y, center.x);//colour of circle
        printf("B: %f G: %f R: %f\n",s.val[0],s.val[1],s.val[2]);

         // 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;
}

1 个答案:

答案 0 :(得分:6)

如果使用C ++界面,则可以使用

cv::cvtColor(img, img, CV_BGR2HSV);

有关详细信息,请参阅the documentation for cvtColor

<强>更新

以缓慢的方式读取和写入像素(假设HSV值存储为cv::Vec3bdoc))

cv::Vec3b pixel = image.at<cv::Vec3b>(0,0); // read pixel (0,0) (make copy)
pixel[0] = 0; // H
pixel[1] = 0; // S
pixel[2] = 0; // V
image.at<cv::Vec3b>(0,0) = pixel; // write pixel (0,0) (copy pixel back to image)

如果你想操纵每个像素,使用image.at<...>(x, y)doc,向下滚动很多)表示法很慢。 documentation on how to access the pixels faster中有一篇文章。您也可以像这样应用迭代器方法:

cv::MatIterator_<cv::Vec3b> it = image.begin<cv::Vec3b>(),
                    it_end = image.end<cv::Vec3b>();
for(; it != it_end; ++it)
{
    // work with pixel in here, e.g.:
    cv::Vec3b& pixel = *it; // reference to pixel in image
    pixel[0] = 0; // changes pixel in image
}