原文链接: opencv 霍夫变换 直线检测
上一篇: opencv 图像梯度 边缘检测
下一篇: opencv 轮廓发现
使用霍夫变换检测图像中存在的直线
对比
import cv2 as cv
import numpy as npimg = cv.imread("tooth.png")
cv.imshow('img', img)gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray, 50, 150, apertureSize=3)
cv.imshow('edge', edges)# 计算直线
lines = cv.HoughLines(edges, 1, np.pi / 180, 180)
tmp = img.copy()
for line in lines:rho, theta = line[0]a = np.cos(theta)b = np.sin(theta)x0 = a * rhoy0 = b * rhox1 = int(x0 + 1000 * (-b))y1 = int(y0 + 1000 * (a))x2 = int(x0 - 1000 * (-b))y2 = int(y0 - 1000 * (a))cv.line(tmp, (x1, y1), (x2, y2), (0, 0, 255), 4)
cv.imshow('line', tmp)# 直接获取线段
lines = cv.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=100, maxLineGap=10)
tmp = img.copy()
for line in lines:x1, y1, x2, y2 = line[0]cv.line(tmp, (x1, y1), (x2, y2), (0, 0, 255), 4)
cv.imshow('line2', tmp)cv.waitKey(0)
cv.destroyAllWindows()