opencv 如何检测和绘制一定Angular 范围内的Hough变换线

lh80um4z  于 2022-11-15  发布在  Angular
关注(0)|答案(1)|浏览(168)

我正在尝试使用概率霍夫变换检测一定Angular 范围内的边缘。我能够检测到线条,但是我的代码没有显示我想要的Angular 范围内的线条。我只是需要一些Python实现过程中的帮助。

def gtob(image):
       cdst = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
       cdstP = np.copy(cdst)
       return cdstP
    

x = segmentation(img)
canny = canny_with_threshold(x)
z = gtob(canny)
theta = np.pi / 180
linesP = cv2.HoughLinesP(canny, 1, theta, 50, None, 150, 10)

if linesP is not None:
    for i in range(0, len(linesP)):
        l = linesP[i][0]
        #p_h = cv2.line(z, (l[0], l[1]), (l[2], l[3]), (0, 0, 255), 3, cv2.LINE_AA)
        x1 = (l[0])
        y1 = (l[1])
        x2 = (l[2])
        y2 = (l[3])
        slope = (y2 - y1) / (x2 - x1)
        angle = math.atan(slope)
        if (angle > 95 and angle < 165):
            m =cv2.line(z, (l[0], l[1]), (l[2], l[3]), (0, 0, 255), 3, cv2.LINE_AA)

cv2.imshow('ses',m)
cv2.waitKey()
jexiocij

jexiocij1#

您可以寻找cv2.HoughLinesP的缐,然后根据Angular 筛选结果。
1.如注解中的beaker所示,math.atan返回以弧度而不是度为单位的Angular 。
1.此外,您可能需要将范围更改为(-90,90)
图像示例:

带有所示Angular 的线(蓝线表示(-45,+45)范围内的Angular ,红线表示其他Angular ):

编码:

import cv2
import numpy as np

image = cv2.imread("lines.jpg")
canny = cv2.Canny(image, 150, 200)

theta = np.pi / 180
linesP = cv2.HoughLinesP(canny, rho=1, theta=theta, threshold=100, minLineLength=100, maxLineGap=100)

used_angles = []
if linesP is not None:
    for line in linesP:
        x1, y1, x2, y2 = line[0]
        slope = (y2 - y1) / (x2 - x1)
        angle = np.math.atan(slope) * 180. / np.pi

        # Skip duplicated angles just for visualization
        similar = sum([np.abs(used_angle - angle) < 2 for used_angle in used_angles])
        if similar:
            continue
        used_angles.append(angle)

        if -45 < angle < 45:
            cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 3, cv2.LINE_AA)
            cv2.putText(image, f'{angle:.2f}', (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)
        else:
            cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 3, cv2.LINE_AA)
            cv2.putText(image, f'{angle:.2f}', (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

cv2.imshow("ses", image)
cv2.waitKey()

相关问题