您可能希望只使用cvCvtColor。
IplImage* dst = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 1);
cvCvtColor(src, dst, CV_RGB2GRAY);
這會將3通道圖像轉換爲單通道灰度圖像。另外,如果你早在你的項目中,我會推薦使用C++ API,因爲它比C API更「笨拙」。
你就可以用下面的代碼同類型節目:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
Mat frame, gray;
VideoCapture video(0);
if(video.isOpened())
{
int key = 0;
do
{
video >> frame;
if(frame.empty())
{
break;
}
cvtColor(frame, gray, CV_BGR2GRAY);
// smooth it, otherwise a lot of false circles may be detected
GaussianBlur(gray, gray, Size(9, 9), 2, 2);
vector<Vec3f> circles;
HoughCircles(gray, circles, CV_HOUGH_GRADIENT,
2, gray.rows/4, 200, 100);
for(size_t i = 0; i < circles.size(); i++)
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
// draw the circle center
circle(frame, center, 3, Scalar(0,255,0), -1, 8, 0);
// draw the circle outline
circle(frame, center, radius, Scalar(0,0,255), 3, 8, 0);
}
namedWindow("circles", 1);
imshow("circles", frame);
key = waitKey(33); // 30Hz video assumed...
} while((char)key != 27); // press ESC to exit
}
return 0;
}
乾淨多了沒有所有的指針同治的:)