Загрузка
Prev Tutorial: Canny Edge Detector
Next Tutorial: Hough Circle Transform
| Original author | Ana Huamán |
| Compatibility | OpenCV >= 3.0 |
In this tutorial you will learn how to:
For Hough Transforms, we will express lines in the Polar system. Hence, a line equation can be written as:
Arranging the terms: \(r = x \cos \theta + y \sin \theta\)
In general for each point \((x_{0}, y_{0})\), we can define the family of lines that goes through that point as:
We consider only points such that \(r > 0\) and \(0< \theta < 2 \pi\).
The three plots intersect in one single point \((0.925, 9.6)\), these coordinates are the parameters ( \(\theta, r\)) or the line in which \((x_{0}, y_{0})\), \((x_{1}, y_{1})\) and \((x_{2}, y_{2})\) lay.
OpenCV implements three kind of Hough Line Transforms:
a. The Standard Hough Transform
b. The Probabilistic Hough Line Transform
c. The Weighted Hough Transform
The sample code that we will explain can be downloaded from here. A slightly fancier version (which shows both Hough standard and probabilistic with trackbars for changing the threshold values) can be found here.
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
// Declare the output variables
Mat dst, cdst, cdstP;
const char* default_file = "sudoku.png";
const char* filename = argc >=2 ? argv[1] : ;
= ( ::( ), );
(.()){
();
(, );
-;
}
(, , , , );
(, , );
= .();
<> ;
(, , , /, , , );
( = ; < .(); ++ )
{
= [][], = [][];
, ;
= (), = ();
= *, = *;
. = ( + *(-));
. = ( + *());
. = ( - *(-));
. = ( - *());
( , , , (,,), , );
}
<> ;
(, , , /, , , );
( = ; < .(); ++ )
{
= [];
( , ([], []), ([], []), (,,), , );
}
(, );
(, );
(, );
();
;
}The sample code that we will explain can be downloaded from here.
import org.opencv.core.*;
import org.opencv.core.Point;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
class HoughLinesRun {
public void run(String[] args) {
// Declare the output variables
Mat dst = new Mat(), cdst = new Mat(), cdstP;
String = ;
= ((. > ) ? [] : );
= .(, .);
( .() ) {
..();
..(
+ +);
.(-);
}
.(, , , , , );
.(, , .);
= .();
= ();
.(, , , ./, );
( = ; < .(); ++) {
= .(, )[],
= .(, )[];
= .(), = .();
= *, = *;
= (.( + *(-)), .( + *()));
= (.( - *(-)), .( - *()));
.(, , , (, , ), , ., );
}
= ();
.(, , , ./, , , );
( = ; < .(); ++) {
[] = .(, );
.(, ([], []), ([], []), (, , ), , ., );
}
.(, );
.(, );
.(, );
.();
.();
}
}
{
([] ) {
.(.);
().();
}
}The sample code that we will explain can be downloaded from here.
"""
@file hough_lines.py
@brief This program demonstrates line finding with the Hough transform
"""
import sys
import math
import cv2 as cv
import numpy as np
def main(argv):
default_file = 'sudoku.png'
filename = argv[0] if len(argv) > 0 else default_file
# Loads an image
src = cv.imread(cv.samples.findFile(filename), cv.IMREAD_GRAYSCALE)
#
:
()
( + + )
-
= .(, , , , )
#
= .(, .)
= .()
= .(, , . / , , , , )
:
(, ()):
= [][][]
= [][][]
= .()
= .()
= *
= *
= (( + *(-)), ( + *()))
= (( - *(-)), ( - *()))
.(, , , (,,), , .)
= .(, , . / , , , , )
:
(, ()):
= [][]
.(, ([], []), ([], []), (,,), , .)
.(, )
.(, )
.(, )
.()
== :
(.[:]) const char* default_file = "sudoku.png";
const char* filename = argc >=2 ? argv[1] : default_file;
// Loads an image
Mat src = imread( samples::findFile( filename ), IMREAD_GRAYSCALE );
// Check if image is loaded fine
if(src.empty()){
printf(" Error opening image\n");
printf(" Program Arguments: [image_name -- default %s] \n", default_file);
return -1;
} String default_file = "../../../../data/sudoku.png";
String filename = ((args.length > 0) ? args[0] : default_file);
// Load an image
Mat src = Imgcodecs.imread(filename, Imgcodecs.IMREAD_GRAYSCALE);
// Check if image is loaded fine
if( src.empty() ) {
System.out.println("Error opening image!");
System.out.println("Program Arguments: [image_name -- default "
+ default_file +"] \n");
System.exit(-1);
} default_file = 'sudoku.png'
filename = argv[0] if len(argv) > 0 else default_file
# Loads an image
src = cv.imread(cv.samples.findFile(filename), cv.IMREAD_GRAYSCALE)
# Check if image is loaded fine
if src is None:
print ('Error opening image!')
print ('Usage: hough_lines.py [image_name -- default ' + default_file + '] \n')
return -1 // Edge detection
Canny(src, dst, 50, 200, 3); // Edge detection
Imgproc.Canny(src, dst, 50, 200, 3, false); dst = cv.Canny(src, 50, 200, None, 3)Now we will apply the Hough Line Transform. We will explain how to use both OpenCV functions available for this purpose.
First, you apply the Transform:
// Standard Hough Line Transform
vector<Vec2f> lines; // will hold the results of the detection
HoughLines(dst, lines, 1, CV_PI/180, 150, 0, 0 ); // runs the actual detection // Standard Hough Line Transform
Mat lines = new Mat(); // will hold the results of the detection
Imgproc.HoughLines(dst, lines, 1, Math.PI/180, 150); // runs the actual detection lines = cv.HoughLines(dst, 1, np.pi / 180, 150, None, 0, 0)And then you display the result by drawing the lines.
// Draw the lines
for( size_t i = 0; i < lines.size(); i++ )
{
float rho = lines[i][0], theta = lines[i][1];
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));
. = ( - *(-));
. = ( - *());
( , , , (,,), , );
} // Draw the lines
for (int x = 0; x < lines.rows(); x++) {
double rho = lines.get(x, 0)[0],
theta = lines.get(x, 0)[1];
double a = Math.cos(theta), b = Math.sin(theta);
double x0 = a*rho, y0 = b*rho;
Point pt1 = new Point(Math.round(x0 + 1000*(-b)), .( + *()));
= (.( - *(-)), .( - *()));
.(, , , (, , ), , ., );
} if lines is not None:
for i in range(0, len(lines)):
rho = lines[i][0][0]
theta = lines[i][0][1]
a = math.cos(theta)
b = math.sin(theta)
x0 = a * rho
y0 = b * rho
pt1 = (int(x0 + 1000*(-b)), int(y0 + 1000*(a)))
pt2 = (int(x0 - *(-)), ( - *()))
.(, , , (,,), , .)First you apply the transform:
// Probabilistic Line Transform
vector<Vec4i> linesP; // will hold the results of the detection
HoughLinesP(dst, linesP, 1, CV_PI/180, 50, 50, 10 ); // runs the actual detection // Probabilistic Line Transform
Mat linesP = new Mat(); // will hold the results of the detection
Imgproc.HoughLinesP(dst, linesP, 1, Math.PI/180, 50, 50, 10); // runs the actual detection linesP = cv.HoughLinesP(dst, 1, np.pi / 180, 50, None, 50, 10)And then you display the result by drawing the lines.
// Draw the lines
for( size_t i = 0; i < linesP.size(); i++ )
{
Vec4i l = linesP[i];
line( cdstP, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, LINE_AA);
} // Draw the lines
for (int x = 0; x < linesP.rows(); x++) {
double[] l = linesP.get(x, 0);
Imgproc.line(cdstP, new Point(l[0], l[1]), new Point(l[2], l[3]), new Scalar(0, 0, 255), 3, Imgproc.LINE_AA, 0);
} if linesP is not None:
for i in range(0, len(linesP)):
l = linesP[i][0]
cv.line(cdstP, (l[0], l[1]), (l[2], l[3]), (0,0,255), 3, cv.LINE_AA) // Show results
imshow("Source", src);
imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst);
imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP); // Show results
HighGui.imshow("Source", src);
HighGui.imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst);
HighGui.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP); cv.imshow("Source", src)
cv.imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst)
cv.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP) // Wait and Exit
waitKey();
return 0; // Wait and Exit
HighGui.waitKey();
System.exit(0); cv.waitKey()
return 0Using an input image such as a sudoku image. We get the following result by using the Standard Hough Line Transform:
And by using the Probabilistic Hough Line Transform:
You may observe that the number of lines detected vary while you change the threshold. The explanation is sort of evident: If you establish a higher threshold, fewer lines will be detected (since you will need more points to declare a line detected).
Meaning that each pair \((r_{\theta},\theta)\) represents each line that passes by \((x_{0}, y_{0})\).