I have matlab code to get Hough transform matrix, theta and rho values.
[H,T,R] = hough(EdgeImage);
How to get H
, T
, R
values in OpenCV?
I have matlab code to get Hough transform matrix, theta and rho values.
[H,T,R] = hough(EdgeImage);
How to get H
, T
, R
values in OpenCV?
In OpenCV, you call the HT as:
vector<Vec2f> lines;
HoughLines(edges, lines, 1, CV_PI/180.0, 100);
where edge
is your binary input image, and lines
is a std::vector
of Vec2f
, i.e. a vector of 2 float values: the first value is rho
, the second one is theta
.
OpenCV doesn't output the H
parameter space, if you need also that you need to write some code yourself and adapt HoughLines
to output also the H
value. However, this is rarely needed in practice.
This is a simple example on how to use standard Hough Transform, adapted from OpenCV tutorials:
#include <opencv2\opencv.hpp>
#include <vector>
using namespace std;
using namespace cv;
int main()
{
// Load image
Mat3b img = imread("path_to_image");
Mat3b res = img.clone();
// Convert to grayscale
Mat1b gray;
cvtColor(img, gray, COLOR_BGR2GRAY);
// Compute edges
Mat1b edges;
Canny(gray, edges, 100, 400);
vector<Vec2f> lines;
HoughLines(edges, lines, 1, CV_PI/180.0, 100);
for (size_t i = 0; i < lines.size(); i++)
{
// rho and theta values
float rho = lines[i][0];
float theta = lines[i][1];
// Draw the line
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(res, pt1, pt2, Scalar(0, 0, 255), 2);
}
imshow("Input", img);
imshow("Output", res);
waitKey();
return 0;
}
Input:
Output: