Detecting lines and circles using the Hough transform
In this recipe, you will learn how to apply the Hough transform for the detection of lines and circles. This is a helpful technique when you need to perform basic image analysis and find primitives in images.
Getting ready
Before you proceed with this recipe, you need to install the OpenCV 3.x Python API package and the matplotlib
package.
How to do it...
- Import the modules:
import cv2 import numpy as np
- Draw a test image:
img = np.zeros((500, 500), np.uint8) cv2.circle(img, (200, 200), 50, 255, 3) cv2.line(img, (100, 400), (400, 350), 255, 3)
- Detect lines using the probabilistic Hough transform:
lines = cv2.HoughLinesP(img, 1, np.pi/180, 100, 100, 10)[0]
- Detect circles using the Hough transform:
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 15, param1=200, param2=30)[0]
- Draw the detected lines and circles:
dbg_img = np.zeros((img.shape[0], img.shape[1], 3), np.uint8) for x1, y1, x2, y2 in lines: print('Detected line: ({} {}) ({} {}...