opencv——霍夫直线检测

1、标准霍夫直线检测

#!/usr/bin/env python3
# -*- coding:UTF8 -*-

"""
标准霍夫直线检测
"""
import cv2 as cv
import numpy as np


def nothing(x):
    pass


img = cv.imread('bmx.jpg')
blur = cv.GaussianBlur(img, (13, 13), -9, -9)
cv.imshow('blur', blur)
gray = cv.cvtColor(blur, cv.COLOR_BGR2GRAY)
cv.imshow('gray', gray)
ret, thresh = cv.threshold(gray, 120, 255, cv.THRESH_BINARY)
cv.imshow('thresh', thresh)
edges = cv.Canny(thresh, 120, 200)
cv.imshow('edges', edges)

cv.waitKey(0)

lines = cv.HoughLines(edges, 1, np.pi / 180, 100)
print(lines)
for line in lines:
    for rho, theta in line:
        # 将(rho,theta)空间的值反映射到直角空间中
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        x1 = int(x0 + 2000 * (-b))
        y1 = int(y0 + 2000 * (a))
        x2 = int(x0 - 2000 * (-b))
        y2 = int(y0 - 2000 * (a))

        cv.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv.imshow('lines', img)

cv.waitKey(0)
cv.destroyWindow('lines')

opencv——霍夫直线检测_第1张图片

2、统计霍夫直线变换

#!/usr/bin/env python3
# -*- coding:UTF8 -*-

"""
统计霍夫直线检测,是标准霍夫变换的一种优化
"""
import cv2 as cv
import numpy as np


def main():
    img = cv.imread('bmx.jpg')
    blur = cv.GaussianBlur(img, (5, 5), -5, -5)
    gray = cv.cvtColor(blur, cv.COLOR_BGR2GRAY)
    ret, thresh = cv.threshold(gray, 180, 255, cv.THRESH_BINARY)
    edges = cv.Canny(thresh, 120, 200)
    cv.imshow('lines', edges)
    cv.waitKey(0)
    lines = cv.HoughLinesP(edges, 1, np.pi / 180, 50, 1000, 5)
    print(lines)
    for line in lines:
        for x1, y1, x2, y2 in line:
            cv.line(img, (x1, y1), (x2, y2), (0, 0, 255), 5)
    cv.imshow('lines', img)
    cv.imwrite('./lines.jpg', img)
    cv.waitKey(0)
    cv.destroyWindow('lines')


if __name__ == '__main__':
    main()

 

你可能感兴趣的:(OpenCV)