taoufik 是正确的,我赞成他的回答。
在阅读他的评论之前,我实际上在 OpenCV 2 Computer Vision Application Programming Cookbook 中找到了答案。
我选择我的答案作为答案,因为它更完整以供将来参考。
@taoufik - 再次感谢,伙计!
我将发布一个可能对其他人有用的代码 sn-p(基于我在食谱中找到的解决方案。我只是编写了简短版本,而不是食谱中的优雅类实现)。
我还在这里添加了一个我写的小函数,它计算 CDF,用于在 Canny 的 Matlab 实现中找到 Canny 边缘检测器的高阈值和低阈值,这给出了很好的结果。通常我也会在边缘检测之前进行高斯模糊(如 Matlab 中的 canny.m 中所示),但附加的图像是综合完美的(无噪声),因此这里是多余的。
我选择了较高的最小投票值(“阈值”),因此只会找到 4 条长线。
我们将从 main 函数中的代码开始:
cv::Mat image = cv::imread("shapes.jpg");
int bins = 256;
cv::Mat cdf = getGrayCDF(image,bins);
cv::Mat diffy = cdf>0.7;
cv::Mat NonZero_Locations; // output, locations of non-zero pixels
cv::findNonZero(diffy, NonZero_Locations);
double highThreshold = double((NonZero_Locations.at<cv::Point>(0).y))/bins;
double lowThreshold = 0.4*highThreshold;
cv::Mat contours;
// cv::GaussianBlur( image, contours, cv::Size(7,7),2 ); // NOT REQUIRED HERE. Syhnthetic image
cv::Canny( image, contours, lowThreshold*bins, highThreshold*bins);
std::vector<cv::Vec4i> lines;
double rho = 1; // delta_rho resolution
double theta = CV_PI/180; // delta_theta resolution
int threshold = 300; // threshold number of votes , I SET A HIGH VALUE TO FIND ONLY THE LONG LINES
double minLineLength = 0; // min length for a line
double maxLineGap = 2; // max allowed gap along the line
cv::HoughLinesP(contours,lines, rho, theta, threshold, minLineLength, maxLineGap); // running probabilistic hough line
if (image.channels()!=3) {cv::cvtColor(image,image,CV_GRAY2BGR);} // so we can see the red lines
int line_thickness = 2;
cv::Scalar color=cv::Scalar(0,0,255);
std::vector<cv::Vec4i>::const_iterator iterator_lines = lines.begin();
while (iterator_lines!=lines.end()) {
cv::Point pt1((*iterator_lines)[0],(*iterator_lines)[1]);
cv::Point pt2((*iterator_lines)[2],(*iterator_lines)[3]);
cv::line( image, pt1, pt2, color, line_thickness);
++iterator_lines;
}
cv::imshow("found lines", image); cvWaitKey(0); cv::destroyWindow("found lines");
我将以计算简单灰度累积分布函数的函数结束:
cv::Mat getGrayCDF(cv::Mat Input, int histSize){
cv::Mat InputGray = Input.clone();
if (InputGray.channels()!=1) {cv::cvtColor(Input,InputGray,CV_BGR2GRAY);}
float range[] = { 0, histSize } ;
const float* histRange = { range };
bool uniform = true; bool accumulate = false;
cv::Mat hist;
calcHist( &InputGray, 1, 0, cv::Mat(), hist, 1, &histSize , &histRange, uniform, accumulate );
for (int i = 1; i < hist.rows; i++) {
float* data = hist.ptr<float>(0);
data[i] += data[i-1];
}
return hist/(InputGray.total()); // WE NOW HAVE A *NORMALIZED* COMPUTED CDF!
}
我对上面给出的 sn-p 的解决方案是:
希望你觉得这很有用!