Skip to content
ImagineWorld

Teaching the Robot to Navigate and Avoid Stairs

node_idnode-book_artificial-intelligence-for-robotics_chapter-07-teaching-the-robot-to-navigate-and-avoid-stairs
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleTeaching the Robot to Navigate and Avoid Stairs
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 7 — Teaching the Robot to Navigate and Avoid Stairs

Section titled “Chapter 7 — Teaching the Robot to Navigate and Avoid Stairs”

Let’s have a quick review of our quest to create a robot that picks up toys. We’ve created a toy detector and trained the robot arm. What’s next on our to-do list? We need to drive the robot to the location of the toy in order to pick it up. That sounds important.

This chapter covers navigation and path planning for our toy-grabbing robot helper. You have to admit that this is one of the most difficult problems in robotics. There are two parts to the task – figuring out where you are (localization), and then figuring out where you want to go (path planning). Most robots at this point would be using some sort of simultaneous localization and mapping (SLAM) algorithm that would first map the room, and then figure out where the robot is within it. But is this really necessary? First of all, SLAM generally requires some sort of 3D sensor, which we don’t have, and a lot of processing, which we don’t want to do. We can also add that it does not use machine learning, and this is a book about artificial intelligence (AI).

Is it possible to perform our task without making maps or ranging sensors? Can you think of any other robot that cleans rooms but does not do mapping? Of course you can. You probably even have a Roomba® (I have three), and most models do not do any mapping at all – they navigate by means of a pseudo-random statistical cleaning routine.

Our task in this chapter is to create a reliable navigation system for our robot that is adaptable to our mission of cleaning a single room or floor of toys, and that uses the sensors we already have.

The following topics will be covered in this chapter:

  • Understanding the SLAM methodology
  • Exploring alternative navigation techniques
  • Introducing the Floor Finder algorithm for avoiding obstacles
  • Implementing neural networks

We require the Robot Operating System Version 2 (ROS 2) for this chapter. This book uses the Foxy Fitzroy release: http://wiki.ros.org/foxy/Installation. This chapter assumes that you have completed Chapter 6, where we gave the robot a voice and the ability to receive voice commands. We will be using the Mycroft interface and voice text-to-speech system, which is called Mimic: https://github.com/MycroftAI/mimic3. You’ll find the code for this chapter in the GitHub repository for this book at https://github.com/PacktPublishing/Artificial-Intelligence-for-Robotics-2e.

We will also be using the Keras library for Python (https://keras.io), which is a powerful library for machine learning applications and lets us build custom neural networks. You can install it using the following command:

pip install keras

You will also need PyTorch, which is installed with this command:

pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

As we do for each chapter, let’s review what we are aiming to accomplish. We will be driving the robot around the house, looking for toys. Once we have a toy, we will take that toy to the toy box and put it away by dropping it into the toy box. Then, the robot will go look for more toys. Along the way, we need to avoid obstacles and hazards, which include a set of stairs going downward that would definitely damage the robot.

Note

I used a baby gate to cover the stairs for the first part of testing and put pillows on the stairs for the second part. There is no need to bounce the robot down the stairs while it is still learning.

We are going to start with the assumption that nothing in this task list requires the robot to know where it is. Is that true? We need to find the toy box – that is important. Can we find the toy box without knowing where it is? The answer is, of course, that the robot can just search for the toy box using its camera until it locates it. We developed a technique for recognizing the toy box back in Chapter 4 with a neural network.

Now, if the robot was doing a bigger job, such as cleaning a 1,000,000-square-foot warehouse, then we would need a map. But our task is to clean a single 16 x 16 room. The time lost searching for the toy box is not all that significant, considering we can’t get too far away, and we must drive to the toy box anyway. We will set this as a challenge, then, to accomplish our task without making a map.

Note

I once oversaw the evaluation of a robot system created at the Massachusetts Institute of Technology. They had a navigation system that did not use a map, and I was quite skeptical. In my defense, the robot actually got lost during the test. Now, I’m making a mapless navigator, and they are welcome to offer critique.

We also need to get the robot to do the following:

  1. Navigate the room avoiding obstacles (toys and furniture) and hazards (stairs).
  2. Find toys in the room (with the toy detector we created earlier).
  3. Drive to a location where the robot arm can reach the toy.
  4. Pick up the toy with the robot arm.
  5. Carry the toy to the toy box.
  6. Put the toy in the toy box.
  7. Go and find another toy.
  8. If there are no more toys, then stop.

We’ve covered finding the toy and picking it up in other chapters. In this chapter, we will discuss driving up to the toy to pick it up.

I’m a big fan of the movie The Princess Bride. It has sword fights, cliffs, two battles of wits, and Rodents of Unusual Size (ROUS). It also has a lesson in planning that we can emulate. When our heroes, Fezzik the Giant, Inigo Montoya, and Westley, plan on storming the castle to rescue the princess, the first things Westley asks are “What are our liabilities?” and “What are our assets?” Let’s do this for our use case:

  • Our liabilities: We have a small robot with a very limited sensor and compute capability. We have a room full of misplaced toys and a set of deadly stairs the robot can fall down.
  • Our assets: We have a robot with omni wheels that can drive around, a voice, one camera, and a robot arm. The robot has a datalink via Wi-Fi to a control computer. We have this book. We have a toy box that is a distinctive color. And lots of Toys of Usual Size (TOUS).

The appropriate next step, whether we are designing robots or invading castles, is to do some brainstorming. How would you go about solving this problem?

We could use SLAM and make a map, then locate the robot on the map, and use that to navigate. Although we ultimately will not be following this method, let’s quickly take a look at how it works.

SLAM is a common methodology for navigating indoor robots. Before we get into the specifics, let’s look at two key issues:

  • The first problem we have in indoor robot driving is that we don’t have a map
  • The second problem we have is that we have no frame of reference to locate ourselves – GPS does not work indoors

That is two problems – we need a map, and then we need a way to locate ourselves on that map. While SLAM starts with the letter S for “simultaneous,” in truth, most robots make a map, store it away, and then drive on it later. Of course, while maps are being made, the robot must make the map and then locate itself on the map – usually in the center.

How does SLAM work? The sensor usually associated with SLAM is the spinning LIDAR. You can think of LIDAR as laser radar – it uses a laser to measure the distance to objects and spins in a circle to collect data all around the robot.

We can summarize the SLAM method as follows:

  1. The robot takes a measurement of the room by sweeping a laser rangefinder in a circle.
  2. The data returned is a list of distance measurements, where the angular measure is a function of the position in the list. If we have a list of 360 measurements in a circle, then the first number in our list is 0 degrees, the next is 1 degree, and so on.
  3. We can extract features in the LIDAR data by looking for corners, edges, jumps, and discontinuities.
  4. We look at the angle and distance to each feature from succeeding measurements and create a function that gives the best estimate of how much the robot moved.
  5. We use that information to transform the LIDAR data from the sensor-centric coordinate system to some sort of room coordinate system, usually by assuming that the starting position of the robot is coordinate 0,0. Our transform, or mathematical transformation, will be a combination of translation (movement) and rotation of the robot’s body frame.
  6. One way of estimating this transform is to use particles. We create samples of the robot’s movement space at every point possible that the robot could have moved, and randomly place dots along all points. We compute the transform for each of these samples and then test to see which sample best fits the data collected. This is called a particle filter and is the technique I use for most of my SLAM projects.

For more details, you can refer to https://www.cs.cmu.edu/~16831-f14/notes/F12/16831_lecture04_dfouhey.pdf.

It can be difficult or impossible for SLAM to work in long, featureless hallways, for instance, as it simply has no information to work with – one lidar sweep looks just like the next. To help with this problem, many SLAM systems require the addition of other sensors to the robot, which measure wheel odometry or use optical flow to measure movement to provide additional data for the position estimate. The following is an illustration of a SLAM map of an office building made with ROS and displayed in RViz. The robot uses 500 particles for each LIDAR sample to estimate which changes in robot position best line up the lidar data with the data in the rest of the map. This is one of my earlier robot projects:

Figure 7.1 – A map generated by a SLAM navigation process

What we have to do in the SLAM process is as follows:

  1. First, take a sweep that measures the distance from the robot to all of the objects in the room.
  2. Then, we move the robot some distance – for example, three inches forward.
  3. Then, we take another sweep and measure the distances again.
  4. We now need to come up with a transformation that converts the data in the second sweep to line up with the data in the first sweep. To do this, there must be information in the two sweeps that can be correlated – corners, doorways, edges, and furniture.

You can get a very small robot LIDAR (e.g., the RPLidar from SLAMtec) for around $100, and use it to make maps. There is an excellent ROS package called Hector Mapping that makes using this LIDAR straightforward. You will find that SLAM is not a reliable process and will require several fits and starts to come up with a map that is usable. Once the map is created, you must keep it updated if anything in the room changes, such are re-arranging the furniture.

The SLAM process is actually very interesting, not for what happens in an individual scan, but in how scans are stitched together. There is an excellent video titled Handheld Mapping in the Robocup 2011 Rescue Arena that the authors of Hector SLAM, at the University of Darmstadt, Germany, put together, illustrating map making. It is available at the following link: https://www.youtube.com/watch?v=F8pdObV_df4list=PL0E462904E5D35E29.

I wanted to give you a quick heads-up on SLAM so that we could discuss why we are not going to use it. SLAM is an important topic and is widely used for navigation, but it is not the only way to solve our problem by any means. The weaknesses of SLAM for our purposes include the following:

  • The need for some sort of sweeping sensor, such as LIDAR, ultrasound, or infrared, which can be expensive, mechanically complicated, and generate a lot of data. We want to keep our robot cheap, reliable, and simple.
  • SLAM often works better if the robot has wheel odometers, which don’t work on omni-wheeled vehicles such as our Albert. Omni wheels slide or skid over the surface in order to turn – we don’t have Ackerman steering, such as a car with wheels that point. When the wheel skids, it is moving over the surface without turning, which invalidates any sort of wheel odometry, which assumes that the wheels are always turning in contact with a surface.
  • SLAM does not deal with floorplans that are changing. The Albert robot has to deal with toys being distributed around the room, which would interfere with LIDAR and change the floorplan that SLAM uses to estimate position. The robot is also changing the floorplan as it picks up toys and puts them away.
  • SLAM is computationally expensive. It requires the use of sensors to develop maps and then compares real-time sensor data to the map to localize the robot, which is a complex process.
  • SLAM has problems if data is ambiguous, or if there are not enough features for the robot to estimate changes on. I’ve had problems with featureless hallways as well as rooms that are highly symmetrical.

So, why did I use this amount of space to talk about SLAM when I’m not going to teach you how to use it? Because you need to know what it is and how it works, because you may have a task that needs to make a map. There are lots of good tutorials on SLAM available, but very few on what I’m going to teach you next, which will be using AI to navigate safely without a map.

Exploring alternative navigation techniques

Section titled “Exploring alternative navigation techniques”

In this section, we’ll look at some potential alternative methods for navigation that we could use for our robot now that we’ve ruled out the SLAM methodology:

  • We could just drive around randomly, looking for toys. When we find a toy, the robot picks it up and then drives around randomly looking for the toy box. When it sees the toy box, it drives up to it and deposits the toy. But we still need a method to avoid running over obstacles. We could follow a process called structure from motion (SfM) to get depth information out of our single camera and use that to make a map. Structure from motion requires a lot of textures and edges, which houses may not have. It also leaves lots of voids (holes) that must be filled in the map. Structure from motion uses parallax in the video images to estimate the distance to the object in the camera’s field of view. There has been a lot of interesting work in this area, and I have used it to create some promising results. The video image has to have a lot of detail in it so that the process can match points from one video image to the next. Here is a survey article on various approaches to SfM, if you are interested you can refer: https://www.ijcit.com/archives/volume6/issue6/IJCIT060609.pdf.
  • You may have heard about a technique called floor finding, which is used in other robots and self-driving cars. I learned a great deal about floor finding from the sophisticated algorithm written by Stephen Gentner in the software package RoboRealm, which is an excellent tool for prototyping robot vision systems. You can find it at http://www.roborealm.com.

This floor finding technique is what we’ll be using in this chapter. Let’s discuss this in detail in the next section.

What I will be presenting in this chapter is my version of a Floor Finder technique that is different from RoboRealm, or other floor-finder algorithms, but that accomplishes the same results. Let’s break this simple concept down for ease of understanding.

We know that the floor directly in front of the robot is free from obstacles. We use the video image pixels of the area just in front of the robot as an example and look for the same texture to be repeated farther away. We are matching the texture of the part of the image we know is the floor with pixels farther away. If the textures match, we mark that area green to show that it is drivable and free of obstacles. We will be using bits of this technique in this chapter. By the way, did you notice that I said texture and not color? We are not matching the color of the floor, because the floor is not all one color. I have a brown carpet in my upstairs game room, which still has considerable variation in coloring. Using color matching, which is simple, just won’t cut it. We have to match the texture, which can be described in terms of color, intensity (brightness), hue, and roughness (a measure of how smooth the color of the surface is).

Let’s try some quick experiments in this area with our image of the floor in my game room. There are several steps involved when doing this for real:

  1. We start with the image we get from the camera. In order to accelerate processing and make the most efficient use of bandwidth, we set the native resolution of our camera – which has a full resolution of 1900 x 1200 – down to a mere 640 x 480. Since our robot is small, we are using a small computer – the Nvidia Jetson Nano.
  2. We move that to our image processing program, using OpenCV, an open source computer vision library that also has been incorporated into ROS.
  3. Our first step is to blur the image using the Gaussian blur function. The Gaussian blur uses a parabolic function to reduce the amount of high-frequency information in the image – it makes the image fuzzier by reducing the differences between neighboring pixels. To get enough blurring, I had to apply the blur function three times with a 5 x 5 convolution kernel. A convolution kernel is a matrix function – in this case, a 5 x 5 matrix of numbers. We use this function to modify a pixel based on its neighbors (the pixels around it). This smoothing makes the colors more uniform, reducing noise, and making the next steps easier. To blur the image, we take a bit from the surrounding pixels – two on either side – and add that to the center pixel. We discussed convolution kernels in Chapter 4.
  4. We designate an area in front of the robot to be an area with a clear view of the floor. I used a triangular area, but a square area works as well. I picked each of the colors found within the triangle and grabbed all of the pixels that had a value with 15 units of that color. What does 15 units mean? Each color is encoded with an RGB value from 0 to 255. Our carpet color, brown, is around 162, 127, and 22 in red, green, and blue units. We select all the colors that are within 15 units of that color, which, for red, is from 147 to 177. This selects the areas of the image similar in color to our floor. Our wall is a very similar brown or beige, but fortunately, there is a white baseboard that we can isolate so that the robot does not try to climb the walls. Color is not the only way to match pixels on our floor. We can also look for pixels with a similar hue (shade of color, regardless of how bright or dark it is), pixels with the same saturation (darkness or lightness of color), and colors with the same value or luminosity (which is the same result as matching colors in a monochrome image or grayscale image). I compiled a chart illustrating this principle:

Figure 7.2 – Selecting pixels in an image by similarity of various attributes, such as color, hue, or saturation

The preceding figure shows the ability of various selection attributes (color, hue, saturation, and luminosity) as a tool to perform floor finding for our robot. The hue attribute seems to provide the best results in this test. I tested it on another image to be sure it was working. It seems not to separate out the baseboards, which are not part of the safe area to drive on.

  1. We select all of the pixels that match our floor colors and paint them green – or, to be more correct, we create a mask region in a copy of the image that has all of the pixels we want to be designated somehow. We can use the number 10, for instance. We make a blank buffer the size of our image and turn all of the pixels in that buffer to 10, which would be the floor in the other image. Performing an erode function on the masked data can help in this regard. There may be small holes or noise where one or two pixels did not match our carpet colors exactly – say there is a spot where someone dropped a cookie. The erode function reduces the level of detail in the mask by selecting a small region – for example, 3 x 3, and setting the mask pixel to 10 only if all of the surrounding pixels are also 10. This reduces the border of the mask by one pixel and removes any small speckles or dots that may be one or two pixels big. You can see from Figure 7*.3* that I was quite successful in isolating the floor area with a very solid mask. Given that we now know where the floor is, we paint the other pixels in our mask red, or some number signifying that it is unsafe to travel there. Let’s use 255:

Figure 7.3 – My version of the floor finder algorithm

Note that it does a very good job in this case of identifying where it is safe to drive. The projected paths are required to prevent the robot from trying to drive up the wall. You get bonus points if you can identify the robot in the corner.

  1. Our next step may take some thought on your part. We need to identify the areas that are safe to drive. There are two cases when using this process that may cause us problems:
    • We may have an object in the middle of the floor by itself – such as a toy – that has green pixels on either side of it
      • We may also have a concave region that the robot can get into but not out of In Figure 7*.3*, you can see that the algorithm painted the wall pixels green since they match the color of the floor. There is a strong red band of no-go pixels where the baseboard is. To detect these two cases, we project lines from the robot’s position up from the floor and identify the first red pixel we hit. That sets the boundary for where the robot can drive. You can get a similar result if you trace upward from the bottom of the image straight up until you hit a red pixel, and stop at the first one. Let’s try the Floor Finder process again, but add some toys to the image so that we can be sure we are getting the result we want:

Figure 7.4 – Adding toys to the image to determine if we are detecting toys as obstacles

That seems to be working well. We are able to find a good path to drive on. Keep in mind that we are constantly updating the obstacle view with the Floor Finder and updating our path as we drive. There is one shortcoming of this process. If a toy matches the color and texture of the carpet, then we might have a lot of difficulty finding it. You can add strip of masking tape to objects to deal with this issue, giving the camera something to see.

  1. Another trick we can use with this process is to use the fixed camera geometry to do distance and size estimates. We have a “locked-down” camera – it is fixed in position on the robot, a set height from the floor, and, therefore, distance along the floor can be measured from the y value of the pixels. We would need to carefully calibrate the camera by using a tape measure and a box to match pixel values to the distance along the same path line we drew from the robot base to the obstacle. The distances will be nonlinear and only valid out to the distance the pixels continue to change. Since the camera is perpendicular to the floor, we get a certain amount of perspective effect that diminishes to 0 about 20 feet from the camera. My calibration resulted in the following table:
    Measurement in inchesDistance from topDistance from bottom
    010800
    12715365
    24627453
    36598.3481.7
    48581.5498.5
    60571.8508.2
    72565515

Table 7.5 – Table of measurements comparing pixels to inches for scale

The following image shows the technique for measuring distance in the robot camera field of view. The object is located four feet away from the robot base along the tape measure. Albert uses a 180-degree fisheye lens on an HD-capable web camera. We need the wide field of view later in Chapter 9 when we do navigation:

Figure 7.5 – Determining the scale of the pixels in our navigation camera image

One thing to watch out for is narrow passages that the robot will not fit into. We can estimate widths based on distance and pixels. One common robot technique is to put a border around all the obstacles equal to 1/2 the width of the robot. If there are obstacles on both sides, then the two borders will meet and the robot will know it does not fit.

In the next section, we will create a convolutional neural network (CNN) to take our images and turn them into robot commands – in essence, teaching our robot how to drive by seeing landmarks or features in the video image.

So, what does a neural network do? We use a neural network to predict some association of an input with an output. When we use a CNN, we can associate a picture with some desired output. What we did in our previous chapter was to associate a class name (toys) with certain images. But what if we tried to associate something else with images?

How about this? We use a neural network to classify the images from our camera. We drive the robot around manually, using a joystick, and take a picture about four times a second. We record what the robot is doing in each picture – going forward, turning right, turning left, or backing up. We use that information to predict the robot’s motion command given the image. We make a CNN, with the camera image as the input and four outputs – commands for go forward, go left, or go right. This has the advantage of avoiding fixed obstacles and hazards automatically. When we get to the stairs (remember that I have stairs going down in my game room that would damage the robot), the robot will know to turn around, because that is what we did in training – we won’t deliberately drive the robot down the stairs during training (right?). We are teaching the robot to navigate the room by example.

You may be yelling at the book at this moment (and you should be) saying, “What about the toys?” Unless, of course, you are following my thought process and thinking to yourself, “Oh, that is why we just spent all that time talking about Floor Finder!” The neural network approach will get us around the room, and avoid the hazards and furniture, but will not help the robot to avoid toys, which are not in the training set. We can’t put them in this training set because the toys are never in the same place twice. We will use the Floor Finder to help avoid the toys. How do we combine the two? The neural network provides the longer-range goal to the robot, and the Floor Finder modifies that goal to avoid local, short-range objects. In our program, we evaluate the neural network first and then use Floor Finder to pick a clear route.

On that theme, we are also going to pull another trick for training our robot. Since our floor surface is subject to change, and may be covered with toys, we will leave that part out of the training images. Before sending the image to the neural network, we’ll cut the image in half and only use the top half. Since our camera is fixed and level with the floor, that gives us only the upper half of the room to use for navigation. Our image is a 180-degree wide angle, so we have a lot of information to work with. This should give us the resiliency to navigate under any conditions:

Figure 7.6 – The training set for driving the robot only includes the top of the image

Our second problem is locating the toy box. For that, we need to create a new training set of images, which will represent an alternative driving pattern. We start the robot in various random locations, and then simply drive to the toy box. We use exactly the same process we used before for navigation – we are creating a training set that tells the robot how to get to the toy box. The trick is to get a good sample of every possible starting location. We do have a bit of a break – if a point on the map (a position in the room) is already on one path, we don’t need to cover it again. In other words, all points that are included in another path don’t need to be repeated. We still want to have at least 1,000 images to train from both sets of images – the one that explores the room, and the set that drives to the toy box.

I created a simple program that just lets the operator drive the robot with a joystick. It automatically takes a snapshot once a second. Each frame is labeled by simply looking at the value for the cmd_vel topic, which is how we control the motion of the robot base. If the angular velocity Z term (angular.z) is positive, we are turning right. If it is negative, we are turning left, and if the term is zero (you guessed it), we are driving straight ahead. I created an independent program that works with the camera and stores a snapshot whenever it receives a TAKE PIC LEFT, RIGHT, CENTER, or BACK command on the ROS syscommand topic. These programs will be in the GitHub repository for the book – I’m not going to include them here. We put each category of picture in its own subdirectory.

You can think of the neural network as working like this:

  1. We present an image to the neural network.
  2. It selects features from that image and then selects the images in the training database that are most like the features in the image provided.
  3. Each picture in the training database is associated with a driving command (left, center, right). So, if the image most closely resembles an image where the robot turned left, then the network will return turn left.

Now let’s look at these processes in greater detail.

Now, we have several steps to take before we can present our data to the neural network for training. Our camera on the robot has way too much resolution for what we need for the network, and we want to use the minimum amount of data in the neural network we can get away with:

Figure 7.7 – Image processing for CNN

Let’s break down this process to make this clearer:

  1. The first image in the preceding figure represents our original image.
  2. Our first step is to downsample the image to 640 x 480. We cut the image in half and keep only the top half, which eliminates the floor from our consideration. We resize the rectangular image to 244 x 244, which is an appropriate size for our neural network to process.
  3. We convert the image to greyscale, so that we only have one channel to process, using this formula (proposed by the National Television Standards Committee (NTSC)): Greyscale = 0.299 * R + 0.587 * G + 0.114 * B
  4. Our next step is to equalize the image to take the entire range of possible values. The raw output of the camera contains neither pure white (255) nor pure black (0). The lowest value may be 53 and the highest, 180, for a range of 127. We scale the grayscale values by subtracting the low (53) and multiplying by the scale factor (127 / 255). This expands the range of the image to the full scale and eliminates a lot of the variation in lighting and illumination that may exist. We are trying to present consistent data to the neural network.
  5. The next step is to perform a Gaussian blur function on the data. We want to reduce some of the high-frequency data in the image, to smooth out some of the edges. This is an optional step, and may not be necessary for your environment. I have a lot of detail in the robot’s field of view, and I feel that the blur will give us better results. It also fills in some of the gaps in the grayscale histogram left by the equalization process in our previous step.
  6. We have to normalize the data to reduce the scale from 0-255 to 0-1. This is to satisfy the artificial neural network’s input requirements. To perform this operation, we just divide each pixel by 255. We also must convert the data from the OpenCV image format to a NumPy array. All of this is part of normal CNN preprocessing.
  7. Our neural network is a nine-layer CNN. I used this common architecture because it is a variation of LeNet, which is widely used for this sort of task (http://vision.stanford.edu/cs598_spring07/papers/Lecun98.pdf). However, in our final step, rather than being a binary output determined by a binary classifier, we will use a Softmax classifier with four outputs – forward, left turn, or right turns. We can actually make more categories if we want to and have easy right and hard right turns rather than just one level of turns. I’m not using the full capability of the new omni wheels on my robot to keep this problem simple. Remember that the number of output categories must match our training set labels exactly. In our CNN, the first six layers are pairs of CNNs with max pooling layers in between. This lets the network deal with incrementally larger details in the image. The final two layers are fully connected with rectified linear units (ReLU) activations. Remember that ReLU only takes the positive values from the other layers. Here is our final layer, which is a Softmax classifier with four outputs:

Figure 7.8 – Organization of our neural network

Like any other neural network training task, the next set of steps in the process involves splitting the input data into training sets and validation sets. Let’s learn how to train the neural network next.

Training the neural network for navigation

Section titled “Training the neural network for navigation”

We’ll use 80% of our data on training and 20% on validation. We really can’t use a process that sweetens the data by duplicating images with random rotations, as we did with the toy recognition program, since we are not just recognizing images, but using them for direction. Changing rotations would mess up our directions.

Now, let’s put our training program together. This program was partially inspired by Adrian Rosebrock’s pyImageSearch blog and by the paper Deep Obstacle Avoidance by Sullivan and Lawson at the Naval Research Lab. You can follow these steps:

  1. We need to collect our training data by driving the robot around and recording our driving movements. This separated our data into three sets – left turn, right turn, and go straight. We have our training images in three subfolders to match our labels. We read in our data, associate it with the labels, and preprocess the data to present it to the neural network.

Note

I’m doing the training runs on my desktop computer, not on the Jetson Nano. We’ll deploy on the Jetson Nano later with our fully trained networks.

  1. Here are the imports that we need for this program – there are quite
    # import the necessary packages
    from keras.preprocessing.image import ImageDataGenerator from keras.optimizers import Adam
    from sklearn.model_selection import train_test_split from keras.preprocessing.image import img_to_array from keras.utils import to_categorical
    import matplotlib.pyplot as plt import numpy as np
    import cv2 import os
    from keras.models import Sequential
    from keras.layers.convolutional import Conv2D
    from keras.layers.convolutional import MaxPooling2D
    from keras.layers.core import Activation
    from keras.layers.core import Flatten
    from keras.layers.core import Dense
    from keras import backend as K
  2. Here is the setup for
    • We have three convolution layers, each followed by a maxpooling layer. Remember that each maxpooling layer will reduce the resolution of the image considered by the network by half, which is ¼ of the data, because we halve the width and the height. The convolution layers use the ReLU activation function since we don’t want any negative pixel values.
      • After the convolution layers, we have two fully connected layers with 500 neurons each.
      • The final layer is our three neuron output layers, with a Softmax classifier that will output the percentage of each classification (left, right, and center). The output will look like (0.8, 0.15, 0.05), with three numbers that add up to 1. This is a generic convolution network class that can be reused for other things, as it is a general multi-class image classification CNN:
    class ConvNet():
    @staticmethod
    def create(width, height, depth, classes):
    # initialize the network
    network = Sequential()
    inputShape = (height, width, depth)
    # first set of CONV => RELU => POOL layers
    network.add(Conv2D(50, (10, 10), padding="same", input_shape=inputShape))
    network.add(Activation("relu"))
    network.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
    # second set of CONV => RELU => POOL layers
    network.add(Conv2D(50, (5, 5), padding="same"))
    network.add(Activation("relu"))
    network.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
    # third set of CONV => RELU => POOL layers
    network.add(Conv2D(50, (5, 5), padding="same"))
    network.add(Activation("relu"))
    network.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
    # Fully connected ReLU layers
    network.add(Flatten())
    network.add(Dense(500))
    network.add(Activation("relu"))
    network.add(Dense(500))
    network.add(Activation("relu"))
    # softmax classifier
    network.add(Dense(classes))
    network.add(Activation("softmax"))
    # return the constructed network architecture
    return network
  3. Now, we set up our learning regime. We will run 25 training runs, with a learning rate of 0.001. We set a batch size of 32 images per batch, which we can reduce if we end up running out
    EPOCHS = 25 LEARN_RATE = 1e-3
    BATCH = 32 # batch size - modify if you run out of memory
  4. The next section loads all of our images. We set the path here where the images reside. We put the three types of training images in folders named left, right, and center:
    print ("Loading Images")
    images=[]
    labels=[]
    #location of your images
    imgPath = "c:\users\fxgovers\documents\book\chapter7\train\" imageDirs=["left","right","center"]
    for imgDir in imageDirs:
    fullPath = imgPath + imgDir
    # find all the images in this directory
    allFileNames =
    os.listdir(fullPath) ifiles=[]
    label = imgDirs.index(imgDir) # use the integer version of the
    label # 0= left, 1 = right, 2 = center
    for fname in allFileNames:
    if ".jpg" in fname:
    ifiles.append(fname)
  5. Now, you can refer back to my diagram (.7) of the process we will go through to preprocess the images. We will cut the image in half and just process the upper half of the picture. Then, we reduce the image to 244 x 244 to fit into the neural network, which needs square images. We will convert the image to grayscale (black and white) since we don’t need to consider color, just shapes. This cuts our data down further. We will equalize the image, which rescales the range of gray colors to fill the whole area from 0 to 255. This evens out the illumination and sets
    # process all of the images
    for ifname in ifiles:
    # load the image, pre-process it, and store it in the data list image = cv2.imread(ifname)
    # let's get the image to a known size regardless of what was collected
    image = cv2.resize(image, (800, 600))
    halfImage = 800*300 # half the pixels
    # cut the image in half -we take the top half
    image = image[0:halfimage]
    #size the image to what we want to put into the neural network image=cv2.resize(image,(224,224))
    # convert to grayscale
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #equalize the image to use the full range from 0 to 255 # this gets rid of a lot of illumination variation
    image = cv2.equalizeHist(image)
  6. Next, we have the Gaussian blur. This is an optional item – you may want to remove it if your room does not have a lot of detail. My game room has lots of furniture, so I think reducing the noise will
    # gaussian blur the image to remove high frequency noise # we use a 5x kernel
    image = cv2.GaussianBlur(img,(5,5),0)
  7. We convert the image to a NumPy array of floats scaled from 0 to 1, instead of a set of integers from 0 to 255. This neural network toolkit only permits NumPy arrays for inputs. We also put the number associated with the labels (left = 0, right= 1, and center = 2) into the matching labels NumPy array:
    # convert to a numpy array image = img_to_array(image)
    # normalize the data to be from 0 to 1
    image2 = np.array(image, dtype="float") / 255.0 images=images.append(image) labels.append(label)
    labels = np.array(labels) # convert to array
  8. We split the data into two parts – a training set that we use to train the neural network, and the testing set that we validate the training set with. We’ll use 80% of the image samples for training and 20%
    # split data into testing data and training data 80/20
    (trainData, testData, trainLabel, testLabel) = train_test_split(data, labels, test_size=0.20, random_state=42)
  9. We have to convert the labels to a tensor, which is just a particular
    # convert the labels from integers to vectors
    trainLabel = to_categorical(trainLabel, num_classes=3) testLabel = to_categorical(testLabel, num_classes=3)
  10. Now, we build our actual neural network by instantiating the ConvNet object, which actually builds our CNN in Keras. We set up the optimizer, which is Adaptive Moment Estimation (ADAM), a type of adaptive gradient descent. ADAM acts against the error gradient like a heavy ball with friction – it has some momentum, but does not pick up
    # initialize the artificial neural network print("compiling CNN...")
    cnn = ConvNet.build(width=224, height=224, depth=1, classes=3) opt = Adam(lr=LEARN_RATE, decay=LEARN_RATE / EPOCHS) model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
  11. We train the network in this step. This will take quite some time to complete – from 15 minutes to an hour or two – depending on how many images you have. We want the training to come out somewhere above 80%. If not, add some epochs to see where the learning curve levels off. If that still does not do the trick, you need more training images. I’m aiming for 1,000 images in each set, which is roughly 50 minutes of driving the
    # train the network
    print("Training network. This will take a while")
    trainedNetwork = model.fit_generator(aug.flow(trainImage, trainLabel, batch_size=BATCH),
    validation_data=(testImage, testLable), steps_per_epoch=len(trainImage) // BATCH,
    epochs=EPOCHS, verbose=1) # save the model to disk
    print("Writing network to disk") cnn.save("nav_model")
  12. We are all done now, so we save the model we created to disk so that we can transfer it to the robot’s computer, the Nvidia Jetson Nano.
  13. Now, make your second training set of driving from random locations to the toy box. Pick random spots and use the joystick to drive the robot to the toy box from each. Keep going until you have 1,000 images or so. Run these through the training program and label this model toybox_model by changing the last line of
    cnn.save("toybox_model")

This is great – we have built and trained our neural network. Now, we need to put it to use to drive the robot around, which we’ll do in the next section.

We need to combine a program that sends out ROS commands with our neural network classification process. I added some commands through the ROS syscommand topic, which I use for non-periodic commands to my robots. syscommand just publishes a string, so you can use it for just about anything. You can follow these steps:

  1. We start with our imports from ROS, OpenCV2, and Keras, as we will be combining functions from all
    import roslib import sys import rospy import cv2
    from std_msgs.msg import String
    from sensor_msgs.msg import Image
    from geometry_msgs.msg import Twist
    from cv_bridge import CvBridge, CvBridgeError
    from keras.preprocessing.image import img_to_array
    from keras.models import load_model
    import numpy as np
  2. This first section is the ROS interface. I like to encapsulate the ROS interface this way, with all of the publish and subscribe in one place. We have several topics to set up – we need to be able to send and receive commands on the syscommand topic. We will be publishing commands to the robot’s motors on the cmd_vel topic. We receive images from the camera on image_topic. We use callbacks to handle the event when a topic is published elsewhere on the robot. These can be called at any time. We have more control when we publish to a topic, which is handled using the pubTwist and pubCmd methods. I added flags to received commands and images so that we don’t accidentally process the same image or command twice:
    class ROSIF():
    def init (self):
    self.bridge = CvBridge()
    self.image_sub = rospy.Subscriber("image_topic",Image,self.callback)
    self.cmd_sub = rospy.Subscriber( "syscommand",String,self.cmdCallback) self.cmd_pub = rospy.Publisher( "syscommand",String,queue_size=10)
    self.twist_pub = rospy.Publisher("cmd_vel",Twist,queue_size=10)
    self.newImage = False
    self.cmdReceived=""
    def callback(self):
    try:
    self.image = self.bridge.imgmsg_to_cv2(data, "bgr8")
    self.newImage = True
    except CvBridgeError as e:
    print(e)
    def cmdCallback(self,data):
    # receieve a message on syscommand
    self.cmdReceived = data.data
    def getCmd(self):
    cmd = self.cmdReceived
    self.cmdReceived = "" # clear the command so we dont do it twice
    return cmd
  3. This next function is the means for the rest of the program to get the latest image from the camera system, which is published on ROS on image_topic. We grab the latest image and set the newImage variable to False, so that we know next time whether we are trying to process the same image twice in a row. Each time we get a new image, we set newImage to True, and each time we use an image, we set newImage to False:
    def getImage(self):
    if self.newImage=True:
    self.newImage = False
    # reset the flag so we don't process twice return self.image
    self.newImage = False
    # we send back a list with zero elements
    img = []
    return img
  4. This section sends speed commands to the robot to match what the CNN output predicts for us to do. The output of the CNN is one of three values: left, right, or straight ahead. These come out of the neural network as one of three enumerated values – 0, 1, or 2. We convert them back to left, right, and center values, and then use that information to send a motion command to the robot. The robot uses the Twist message to send motor commands. The Twist data message is designed to accommodate very complex robots, quadcopters, and omni-wheel drive systems that can move in any direction, so it has a lot of extra values. We send a Twist.linear.x command to set the speed of the robot forward and backward, and a Twist.angular.z value to set the rotation, or turning, of the base. In our case, a positive angular.z rotation value goes to the right, and a negative value to the left. Our last statement publishes the data values on the cmd_vel topic as a Twist message:
    # publishing commands back to the robot
    def pubCmd(self,cmdstr):
    self.cmd_pub.publish(String(cmdstr)):
    def pubTwist(self,cmd):
    if cmd == 0: # turn left
    turn = -2
    speed = 1
    if cmd==1:
    turn = 2
    speed = 1
    if cmd ==3:
    turn=0
    speed = 1 # all stop
    if cmd==4:
    turn = 0
    speed = 0
    cmdTwist = Twist()
    cmdTwist.linear.x = speed
    cmdTwist.angular.z = turn self.twist_pub.publish(cmdTwist)
  5. We create a function to do all of our image processing with one command. This is the exact replica of how we preprocessed the images for the training program – just as you might think. You may think it a bit strange that I scale the image up, only to then scale it down again. The reason for this is to have detail for the vertical part of the image. If I scaled it down to 240 x 240 and then cut it in half, I would be stretching pixels afterward to get it square again. I like having extra pixels when scaling down. The big advantage of this technique is that it does not matter what resolution the incoming image is at – we will end up with the correctly sized and The other steps involve converting the image to grayscale, performing an equalization on the contrast range, which expands our color values to fill the available space, and performing a Gaussian blur to reduce noise. We normalize the image for the neural network by converting our integer 0-255 grayscale values to floating point values from 0 to 1:
    def processImage(img):
    # need to process the image
    image = cv2.resize(image, (640, 480))
    halfImage = 640*240 # half the pixels
    # cut the image in half -we take the top half image = image[0:halfimage]
    #size the image to what we want to put into the neural network
    image=cv2.resize(image,(224,224))
    # convert to grayscale
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    #equalize the image to use the ful
    image = cv2.equalizeHist(image)
    # gaussian blur the image to remove high freqency noise # we use a 5x kernel
    image = cv2.GaussianBlur(img,(5,5),0) # convert to a numpy array
    image = img_to_array(image)
    # normalize the data to be from 0 to 1
    image2 = np.array(image, dtype="float") / 255.0 return image2
  6. Now that we’re set up, we go into the main program. We have to initialize our ROS node so that we can talk to the ROS publish/subscribe system. We create a variable, mode, that we use to control what branch of processing to go down. We make an interface to allow the operator to turn the navigation function on and off, and to select between normal navigation and our In this first section, we will load both neural network models that we trained before:
    # MAIN PROGRAM
    ic = image_converter()
    rosif = ROSIF()
    rospy.init_node('ROS_cnn_nav')
    mode = "OFF"
    # load the model for regular navigation
    navModel = load_model("nav_model")
    toyboxModel = load_model("toybox_model")
  7. This section begins the processing loop that runs while the program is active. Running rospy.spin() tells the ROS system to process any message that may be waiting for us. Our final step is to pause the program for 0.02 seconds to allow the Raspberry Pi to process other data and run
    while not rospy.is_shutdown():
    rospy.spin()
    time.sleep(0.02)

So, that concludes our navigation chapter. We’ve covered both obstacle avoidance and room navigation using a neural network to teach the robot to drive about using landmarks on the ceiling – and without a map.

This chapter introduced some concepts for robot navigation in an unstructured environment, which is to say, in the real world, where the designers of the robot don’t have control over the content of the space. We started by introducing SLAM, along with some of the strengths and weaknesses of map-based navigation. We talked about how Roomba navigates, by random interaction and statistical models. The method selected for our toy-gathering robot project, Albert, combined two algorithms that both relied mostly on vision sensors.

The first was the Floor Finder, a technique I learned when it was used by the winning entry in the DARPA Grand Challenge. The Floor Finder algorithm uses the near vision (next to the robot) to teach the far vision (away from the robot) what the texture of the floor is. We can then divide the room into things that are safe to drive on, and things that are not safe. This deals with our obstacle avoidance. Our navigation technique used a trained neural network to identify the path around the room by associating images of the room from the horizon up (the top half of the room) with directions to travel. This also served to teach the robot to stay away from the stairs. We discarded the bottom half of the room from the image for the neural network because that is where the toys are. We used the same process to train another neural network to find the toy box.

This process was the same as we saw in Chapter 4, but the training images were all labeled with the path from that spot to the toy box. This combination gave us the ability to teach the robot to find its way around by vision, and without a map, just like you do.

In the next chapter, we’ll cover classifying objects, and review some other path-planning methods.

  1. Regarding SLAM, what sensor is most commonly used to create the data that SLAM needs to make a map?
  2. Why does SLAM work better with wheel odometer data available?
  3. In the Floor Finder algorithm, what does the Gaussian blur function do to improve the results?
  4. The final step in the Floor Finder is to trace upward from the robot position to the first red pixel. In what other way can this step be accomplished (referring to Figure 7*.3*)?
  5. Why did we cut the image in half horizontally before doing our neural network processing?
  6. What advantages does using the neural network approach provide that a technique such as SLAM does not?
  7. If we used just a random driving function instead of the neural network, what new program or function would we have to add to the robot to achieve the same results?
  8. How did we end up avoiding the stairs in the approach presented in the chapter? Do you feel this is adequate? Would you suggest any other means for accomplishing this task?
  • Deep Obstacle Avoidance by Sullivan and Lawson, published by Naval Research Labs, Rosebrock, Adrian.
  • Artificial Intelligence with Python Cookbook by Ben Auffarth, Packt Publishing, 2020
  • Artificial Intelligence with Python – Second Edition, by Prateek Joshi, Packt Publishing, 2020
  • Python Image Processing Cookbook by Sandipan Dey, Packt Publishing, 2020