霍夫直线变换
cv2.HoughLines(image, rho, theta, threshold, lines, sen, stn, min_theta, max_theta)
cv2.HoughLines()。返回值就是极坐标表示的直线(ρ, θ)。ρ 的单位是像素,θ 的单位是弧度。
def line_detect_possible_demo():
"""使用霍夫直线变换做直线检测"""
img_path = './line.png'
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
# 函数将通过步长为1的半径和步长为π/180的角来搜索所有可能的直线
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=50, maxLineGap=10)
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.imshow("line_detect_possible_demo", img)
def circular_detect():
"""霍夫变换圆检测"""
import cv2
# 参考链接https://www.it610.com/article/1281199971172892672.htm
# 载入并显示图片
img = cv2.imread('./circular.png')
# 灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 输出图像大小,方便根据图像大小调节minRadius和maxRadius
print(img.shape)
ret, thresh1 = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
cv2.imshow('thresh1', thresh1)
canny = cv2.Canny(thresh1, 40, 80)
cv2.imshow('Canny', canny)
canny = cv2.blur(canny, (3, 3))
cv2.imshow('blur', canny)
# 霍夫变换圆检测
circles = cv2.HoughCircles(canny, cv2.HOUGH_GRADIENT, 1, 100, param1=50, param2=30, minRadius=30, maxRadius=150)
# 输出返回值,方便查看类型
print(circles)
# 输出检测到圆的个数
print(len(circles[0]))
# 根据检测到圆的信息,画出每一个圆
for circle in circles[0]:
if (circle[2] >= 100):
continue
# 圆的基本信息
print(circle[2])
# 坐标行列
x = int(circle[0])
y = int(circle[1])
# 半径
r = int(circle[2])
# 在原图用指定颜色标记出圆的位置
img = cv2.circle(img, (x, y), r, (0, 0, 255), -1)
# 显示新图像
cv2.imshow('circular_detection', img)