首页 > 解决方案 > 查找使用 OpenCV 检测到的线的角度

问题描述

我正在将 OpenCV 用于机器人视觉项目 - 导航迷宫。我可以检测出迷宫墙壁与地板相接的线条。现在需要使用这些检测到的线来计算机器人应该转向哪个方向。

为了确定机器人应该以哪种方式移动,我认为解决方案是计算墙壁相对于机器人位置的角度。但是,在找到两面墙的地方,我如何选择要用作参考的点。

我知道我可以使用 python atan2 公式来计算两点之间的角度,但之后我完全迷失了。

这是我的代码:

    # https://towardsdatascience.com/finding-driving-lane-line-live-with-opencv-f17c266f15db
# Testing edge detection for maze
import cv2
import numpy as np
import math

image = cv2.imread("/Users/BillHarvey/Documents/Electronics_and_Robotics/Robot_Vision_Project/mazeme/maze1.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
kernel_size = 5
blur_gray = cv2.GaussianBlur(gray,(kernel_size,kernel_size),0)
low_threshold = 50
high_threshold = 150

edges = cv2.Canny(blur_gray, low_threshold, high_threshold)

# create a mask of the edges image using cv2.filpoly()
mask = np.zeros_like(edges)
ignore_mask_color = 255

# define the Region of Interest (ROI) - source code sets as a trapezoid for roads
imshape = image.shape

vertices = np.array([[(0,imshape[0]),(100, 420), (1590, 420),(imshape[1],imshape[0])]], dtype=np.int32)

cv2.fillPoly(mask, vertices, ignore_mask_color)
masked_edges = cv2.bitwise_and(edges, mask)

# mybasic ROI bounded by a blue rectangle

#ROI = cv2.rectangle(image,(0,420),(1689,839),(0,255,0),3)

# define the Hough Transform parameters
rho = 2 # distance resolution in pixels of the Hough grid
theta = np.pi/180 # angular resolution in radians of the Hough grid
threshold = 15     # minimum number of votes (intersections in Hough grid cell)
min_line_length = 40 #minimum number of pixels making up a line
max_line_gap = 30    # maximum gap in pixels between connectable line segments

# make a blank the same size as the original image to draw on
line_image = np.copy(image)*0 

# run Hough on edge detected image
lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]),min_line_length, max_line_gap)

for line in lines:
        for x1,y1,x2,y2 in line:
            cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10)
            angle = math.atan2(x2-x1, y2-y1)
            angle = angle * 180 / 3.14
            print("Angle = ", angle) 

# draw the line on the original image 
lines_edges = cv2.addWeighted(image, 0.8, line_image, 1, 0)
#return lines_edges

#cv2.imshow("original", image)
#cv2.waitKey(0)

#cv2.imshow("edges", edges)
#cv2.waitKey(0)

cv2.imshow("detected", lines_edges)
cv2.waitKey(0)

cv2.imwrite("lanes_detected.jpg", lines_edges)
cv2.destroyAllWindows()

我在 HoughLinesP 检测到线条的地方绘制了蓝线的代码段中添加了 athn2 forumla。

并将结果(角度)转换为度数,我找到了这个公式:

angle = angle * 180 / 3.14

下面的一段代码:

print("Angle = ", angle)

打印 13 个角度,这些角度可能与图片中的线条相等,也可能不相等,是吗?为了避免获得 - 度,我不得不做 x2-x1, y2-y1 而不是我在其他地方看到的其他方式。

对于我根本缺乏 Python 和数学知识,我深表歉意,但我们将不胜感激地收到任何帮助。

检测到的车道

标签: pythonopencv

解决方案


推荐阅读