概述
黑马程序员人工智能教程_10小时学会图像处理OpenCV入门教程中,3.6霍夫线检测代码,对于直线绘制的局部,没有看懂,这里,依据本人的了解,对直线绘制的代码进行了实现。
原理与实现
对于笛卡尔坐标系下y = ax + b
,转换成极坐标系下有rho = x * cos(theta) + y * sin(theta)
,
两边除以sin(theta)失去下式:y = - cos(theta) / sin(theta) * x + rho / sin(theta)
当sin(theta) ==0时,有x = rho / cos(theta)
当sin(theta) !=0时,有a = - cos(theta) / sin(theta) ; b = rho / sin(theta)
由a, b能够失去直角坐标系下直线方程,能够失去两个点,即可画出直线。
在图像上绘制直线的代码如下所示,最初的成果,与老师视频中的成果统一。代码如下所示
print('lines.shape =', lines.shape)h, w = img.shape[:2]for line in lines: rho, theta = line[0] if math.sin(theta) == 0: x = int(rho / math.cos(theta)) cv.line(img, (x, 0), (x, h - 1), (0, 255, 0)) else: a = - math.cos(theta) / math.sin(theta) b = rho / math.sin(theta) # y = a * x + b,计算直线中两个点 x1 = 0 y1 = int(b) x2 = w - 1 y2 = int(a * x1 + b) cv.line(img, (x1, y1), (x2, y2), (0, 255, 0))
参考文献
https://zhuanlan.zhihu.com/p/... (hough变换原理以及实现(转载) - 知乎)