查找使用OpenCV检测到的线的角度

时间:2018-11-13 18:50:51

标签: python 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()

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

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

angle = angle * 180 / 3.14

以下代码:

print("Angle = ", angle)

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

我对自己根本缺乏python和数学知识表示歉意,但将不胜感激地得到任何帮助。

Lanes Detected

0 个答案:

没有答案