Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 54 ยท Edges, Contours and Shapes

Detecting Lines, Circles and Shapes

Detect lines with HoughLines and HoughLinesP, circles with HoughCircles, and classify polygons with approxPolyDP. See the Hough accumulator in NumPy.

Edges and contours tell you where the boundaries are, but often you want something more structured: "this is a straight line", "this is a circle with radius 40", "this contour is a triangle". OpenCV answers these questions in two different ways. The Hough transform finds lines and circles directly from an edge map by letting every edge pixel vote. Polygon approximation takes a contour you already have and simplifies it into a few corner points, and the number of corners tells you the shape.

This lesson covers cv2.HoughLines, cv2.HoughLinesP, cv2.HoughCircles and cv2.approxPolyDP. The real functions are shown as read-only code, because opencv-python cannot run in the browser. The stand-ins build the Hough accumulator in NumPy and implement polygon simplification in Python, so you can see why these methods work and what their parameters really control.

The stand-ins are teaching versions: they find the same kinds of answers (peaks in an accumulator, simplified polygons) with simple code. OpenCV's versions add gradient information, probabilistic sampling and many optimizations, so exact numbers on real photos will differ.

Two ways to find shapes

Hough voting Edge pixels vote for lines and circles.
Polygon approximation Simplify a contour to its corners.
1 / 2

Hough lines: voting in rho-theta space

A straight line can be described by two numbers: rho, its distance from the origin, and theta, the angle of its normal. A point (x, y) lies on the line when rho = x*cos(theta) + y*sin(theta). Turn this around: for one edge pixel, every line passing through it is a pair (rho, theta), and as theta sweeps from 0 to 179 degrees the matching rho traces a curve. Draw that curve into a table (the accumulator) by adding 1 to each cell it passes through. Do this for every edge pixel. Pixels that lie on the same line produce curves that cross in one cell, so that cell collects many votes. Peaks in the accumulator are the lines.

Python A Hough accumulator for lines and circles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The picture has two lines (43 edge pixels in total) and the accumulator finds both. The horizontal line y = 10 becomes the peak rho = 10 at about 90 degrees (the normal of a horizontal line points straight down); it prints 89 because 89 and 90 degrees tie at 24 votes and argmax returns the first. The diagonal y = x passes through the origin, so rho = 0 and its normal points at 135 degrees, with 20 votes, one per pixel. After each peak we blank its neighborhood, the same non-maximum idea as in Canny Edge Detection, or the next-best peak would just be a neighbor of the first.

The second half does the same for circles. If the radius is known, every edge point can only belong to circles whose center is exactly one radius away from it, so each point votes for a ring of candidate centers. All 64 edge points agree on one center, the true one at row 22, column 17, which collects 52 votes. (The votes fall short of 64 because rounding to whole pixels moves some votes into neighboring cells.) OpenCV's HOUGH_GRADIENT method avoids the extra radius dimension by using the gradient direction of each edge pixel to vote along a single line, then estimates the radius in a second step.

The OpenCV functions

Python
import cv2
import numpy as np

gray = cv2.imread("road.png", cv2.IMREAD_GRAYSCALE)
edges = cv2.Canny(cv2.GaussianBlur(gray, (5, 5), 1.4), 50, 150)

# Standard Hough: returns (rho, theta) for every line found
lines = cv2.HoughLines(edges, 1, np.pi / 180, threshold=120)
for rho, theta in (lines[:, 0] if lines is not None else []):
    a, b = np.cos(theta), np.sin(theta)
    x0, y0 = a * rho, b * rho
    p1 = (int(x0 + 1000 * (-b)), int(y0 + 1000 * a))
    p2 = (int(x0 - 1000 * (-b)), int(y0 - 1000 * a))
    cv2.line(img, p1, p2, (0, 0, 255), 2)

# Probabilistic Hough: returns segments (x1, y1, x2, y2)
segments = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=50,
                           minLineLength=40, maxLineGap=10)

The arguments mean:

  • rho (1) and theta (np.pi / 180) are the accumulator resolution in pixels and radians. Finer resolution spreads the votes over more cells, so the threshold must come down.
  • threshold is the minimum number of votes for a line. Lower finds more (including false) lines; higher finds fewer.
  • For HoughLinesP, minLineLength drops short segments and maxLineGap joins collinear segments with gaps smaller than this value.

The standard HoughLines returns infinite lines, which is why the drawing code stretches the line far past the point (x0, y0). HoughLinesP returns real segments with end points, which is usually what you want for lane lines or document edges. Both return None when nothing is found, so check for that before indexing.

Circles

Python
blur = cv2.medianBlur(gray, 5)
circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, dp=1.2, minDist=40,
                           param1=100, param2=40, minRadius=10, maxRadius=80)
if circles is not None:
    for x, y, r in np.round(circles[0]).astype(int):
        cv2.circle(img, (x, y), r, (0, 255, 0), 2)

HoughCircles takes the grayscale image and runs its own Canny internally: param1 is the upper Canny threshold, and param2 is the accumulator threshold (smaller means more, and more false, circles). minDist is the minimum distance between centers, and minRadius and maxRadius restrict the search, which also makes it faster and more reliable; always set them if you roughly know the size. The result has shape (1, N, 3), one (x, y, radius) per circle, or None.

Polygon approximation with approxPolyDP

Suppose a contour has 200 points but is really a rectangle with slightly wobbly sides. cv2.approxPolyDP(cnt, epsilon, True) simplifies it with the Ramer-Douglas-Peucker algorithm: draw a line between the two end points; find the contour point farthest from the line; if it is farther than epsilon, keep it and recurse on both halves; otherwise drop everything in between. What remains is a handful of corner points. epsilon is the allowed deviation in pixels, normally chosen as a fraction of the perimeter:

Python
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
corners = len(approx)

The number of corners classifies simple shapes: 3 is a triangle, 4 a rectangle or square, 5 a pentagon, and many corners (6 or more) is usually a circle or ellipse. To split squares from rectangles, check the aspect ratio of cv2.boundingRect, as in Contour Features.

Python Simplify a contour and classify shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Dozens of contour points collapse to 3, 4, 4 and 5 corners for the triangle, the square, the stretched rectangle and the pentagon, and the aspect-ratio check separates square from rectangle. The circle keeps 7 vertices at the 4% setting, which the classifier treats as "many corners, so a circle". The last four lines are the important lesson: epsilon changes the answer. At 0.5% the circle keeps 17 vertices, and at 10% only 4, so a circle would be misread as a square. A fraction between 1% and 4% of the perimeter is the usual range; tune it on your own images and keep it the same for all shapes.

Choosing between the tools

  • Straight structures in a noisy edge map (lanes, building edges, page borders): HoughLinesP.
  • Coins, pupils, balls: HoughCircles, with blur and a radius range. If the objects are separate blobs, the contour measurements from Contour Features (circularity, minimum enclosing circle) are often more robust than Hough.
  • Clean, isolated shapes (a logo, a worksheet of triangles and squares): contours plus approxPolyDP.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the Hough line transform, what does each edge pixel do?

    Each edge pixel increments all accumulator cells (rho, theta) of the lines through it. Real lines show up as cells with many votes.
  2. 2. Which function returns line segments with end points rather than infinite lines?

    HoughLinesP is the probabilistic version. It returns (x1, y1, x2, y2) for each segment, and its minLineLength and maxLineGap control how segments are kept and joined.
  3. 3. What does the epsilon argument of cv2.approxPolyDP control?

    epsilon is the allowed deviation in pixels (usually a small fraction of the perimeter). A larger epsilon removes more points and gives a rougher polygon.
  4. 4. You pass a color image to cv2.HoughCircles and get an error or poor results. What is the best fix?

    HoughCircles needs an 8-bit single-channel image, and a light blur reduces noise that creates false circles.
  5. 5. A contour approximates to 4 vertices with a bounding box of 40 by 80. What is it most likely?

    Four corners mean a quadrilateral. The aspect ratio of 0.5 is far from 1, so it is a rectangle rather than a square.

Summary

  • Hough transforms let edge pixels vote in a parameter space; peaks in the accumulator are lines (rho, theta) or circles (center, radius).
  • cv2.HoughLines returns infinite lines, cv2.HoughLinesP returns segments; threshold, minLineLength and maxLineGap tune them.
  • cv2.HoughCircles needs a blurred grayscale image; set minDist, minRadius and maxRadius for stable results.
  • cv2.approxPolyDP simplifies a contour with Ramer-Douglas-Peucker; the corner count (plus aspect ratio) classifies simple shapes.
  • Choose epsilon as a small fraction of the perimeter and check it on your own images.

Next lesson: Template Matching.