Hough变换
#include<opencv2/opencv.hpp>
cv::Mat hough(cv::Mat src, std::vector<cv::Vec2f> lines) {
cv::HoughLines(src, lines, 1, CV_PI / 180, 300, 0, 0);
cv::Mat dst;
cv::cvtColor(src, dst, CV_GRAY2BGR);
for (size_t i = 0; i < lines.size(); i++) {
float rho = lines[i][0], theta = lines[i][1];
cv::Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a * rho, y0 = b * rho;
pt1.x = cvRound(x0 + 1000 * (-b));
pt1.y = cvRound(y0 + 1000 * (a));
pt2.x = cvRound(x0 - 1000 * (-b));
pt2.y = cvRound(y0 - 1000 * (a));
line(dst, pt1, pt2, cv::Scalar(0, 0, 255), 1, cv::LINE_AA);
}
return dst;
}
cv::Mat houghP(cv::Mat src, std::vector<cv::Vec4i> linesP) {
cv::Mat dst;
cv::cvtColor(src, dst, CV_GRAY2BGR);
HoughLinesP(src, linesP, 1, CV_PI / 180, 50, 50, 10);
for (size_t i = 0; i < linesP.size(); i++)
{
cv::Vec4i l = linesP[i];
line(dst, cv::Point(l[0], l[1]), cv::Point(l[2], l[3]),
cv::Scalar(0, 0, 255), 1, cv::LINE_AA);
}
return dst;
}
cv::Mat houghC(cv::Mat src) {
cv::Mat gray;
cv::cvtColor(src, gray, CV_BGR2GRAY);
cv::Mat thresh;
cv::threshold(gray, thresh, 0, 255, CV_THRESH_BINARY_INV | CV_THRESH_OTSU);
std::vector<cv::Vec3f> circles;
circles.reserve(src.cols * src.rows);
cv::HoughCircles(gray, circles, CV_HOUGH_GRADIENT, 1, 100, 220, 30, 150, 200);
for (size_t i = 0; i < circles.size(); i++)
{
cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
circle(src, center, 3, cv::Scalar(0, 255, 0), -1, 8, 0);
circle(src, center, radius, cv::Scalar(0, 0, 255), 1, 8, 0);
}
return src;
}
int main() {
cv::Mat build = cv::imread("D:\\pic\\xian.jpg");
cv::Mat moon = cv::imread("D:\\pic\\moon.jpg");
cv::Mat build_gray, build_gray_canny, build_gray_thresh;
cv::cvtColor(build, build_gray, CV_BGR2GRAY);
cv::threshold(build_gray, build_gray_thresh, 0, 255, CV_THRESH_BINARY_INV | CV_THRESH_OTSU);
cv::Canny(build, build_gray_canny, 50, 200, 3);
std::vector<cv::Vec2f> lines;
std::vector<cv::Vec4i> linesP;
lines.resize(build.rows * build.cols);
linesP.resize(build.rows * build.cols);
cv::Mat thresh_hough = hough(build_gray_thresh, lines);
cv::Mat canny_hough = hough(build_gray_canny, lines);
cv::Mat thresh_houghP = houghP(build_gray_thresh, linesP);
cv::Mat canny_houghP = houghP(build_gray_canny, linesP);
cv::Mat moon_houghC = houghC(moon);
return 0;
}