原理参考:
https://blog.csdn.net/saltriver/article/details/80547245
官方指导:
https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html
**如果x-y图像空间中有很多点在k-b空间中相交于一点(即x-y图像空间中有很多的点同属于一对儿k-b),那么这个交点就是我们要检测的直线。**这就是霍夫变换检测直线的基本原理。
转换到极坐标下
视频源码:
import cv2 as cv
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# # 尝试画出这样的图像:
# # 对于公式 r = x * cos(theta) + y * sin(theta)
# # 在图像坐标空间选定一个点(x, y) = (1, 1),画出该点在极坐标下(或直角坐标系下 )所对应的一族(r, theta),
# # 即 r = cos(theta) + sin(theta) 在极坐标下的图像。
# mpl.rcParams["font.sans-serif"] = ["SimHei"]
# pi = np.pi
# theta = np.arange(0, 2 * pi, 0.02) # 极角,弧度制
# r = np.sin(theta) + np.cos(theta)
# plt.figure()
# # ax = plt.gca(projection='polar')
# plt.plot(theta, r, "g-")
#
# plt.show()
#
# print(np.sin(1 / 4 * np.pi) + np.cos(1 / 4 * np.pi))
# print(np.sin(5 / 4 * np.pi) + np.cos(5 / 4 * np.pi))
def line_detection(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray, 50, 150, apertureSize=3)
cv.imshow("edges", edges)
lines = cv.HoughLines(edges, 1, np.pi / 180, 200) # 200是指当极坐标下有超过200个曲线交于同一个点时该点才被认为是图像空间的一条直线
for line in lines:
rho, theta = line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
x1 = np.int(x0 + 1000 * (-b))
y1 = np.int(y0 + 1000 * a)
x2 = np.int(x0 - 1000 * (-b))
y2 = np.int(y0 - 1000 * a)
cv.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv.imshow("image lines", image)
def line_detect_possible_demo(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray, 50, 150, apertureSize=3)
cv.imshow("edges", edges)
# maxLineGap=10代表这条线最多断10个像素,我还认为它是一条线,再多断点就不把他再当做一条直线
# HoughLinesP() 中的 minLineLength 和 maxLineGap 两个参数非常重要,可以提升你提取直线的精准性,
# 一般我们都用这个 HoughLinesP() 来call,因为它会告诉你一条线的两个端点左边,而 HoughLines() 不会
lines = cv.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=50, maxLineGap=10)
for line in lines:
print(type(line))
x1, y1, x2, y2 = line[0]
cv.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv.imshow("line_detect_possible_demo", image)
print("-----------Python OpenCV Tutorial--------------")
src = cv.imread("C:/cv-samples/data/sudoku.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
# line_detection(src)
line_detect_possible_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()