《python+opencv3.3视频教学 基础入门》霍夫变换(直线检测) 笔记

25 篇文章 0 订阅
15 篇文章 0 订阅

原理参考:
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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值