A Rapidly-Exploring Random Tree is a randomised data structure that is designed for path planning problems.
In any image where RRT has to be implemented, there will be a start point, an end point and obstacles. The start point is taken as the first node, and the end point is taken as the last node. The first step is to generate a random node. Using distance formula, the node (in the tree) which has the minimum distance from this random node among all other nodes in the tree is identified. Starting from the nearest node, in the direction of the random node, a new node is generated at a predefined distance called step size. This new node is then added to the tree. These steps are repeated n number of times till the end point is added to the tree. Then a continuous path is traced from the start point to the end point which successfully avoids all obstacles. This process results into a tree-like structure, hence the name Rapidly-Exploring Random Tree.
The code explained
Let us take a sample image to implement the code on.
Following are some basic declarations:
init() function declares the position of the start point and the end point. The start point is marked blue and the end point red.
near_node function is responsible for finding the nearest node in the tree for a particular random node (
node_dist function takes two coordinates as its input and returns the distance between them.
The stepping function takes the random node generated (
rnode) and its nearest node (
nnode) in the tree as its input, and returns the coordinates of the step node. This function determines the step node by generating a new node at a distance of
step_node as inputs. They check if the step node that has been generated is valid or not. It will be invalid if the step node either lies on a black pixel (that is, an obstacle) or if the straight line path joining
nnode and step node goes through an obstacle.
0 is returned in case step node is invalid and
1 is returned in case step node is valid.
draw_path draws the final path starting from the
end_node to the
start_node in green color.
rrt() function executes the entire process of generating the random nodes and making the tree.
Generation of a random point:
Index indicates the nearest node for a randomly generated node.
index = near_node(*rnode);
Calling the stepping function to obtain the step node:
Checking the validity of the step node. If valid, then both
flag2 would equal
If the stepnode is valid, then stepnode is added to the tree:
Joining the stepnode to the tree by a yellow line:
Marking the stepnodes green:
end_node is added to the tree if it fits the validity criteria and the distance between the
end_node and the last step node is less than the
Final path is drawn in green:
draw_path(); Iteration number is incremented:
iter++; Here is the output image after the implementation of the code: