bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
A line following robot with a Raspberry Pi camera

In A differential drive robot with real motors real motors moved a simulated robot. Here a camera on a Raspberry Pi 5 guides it. The Pi streams pictures of a line drawn on paper, and each picture is the floor of the simulated world. The differential drive robot of A differential drive robot in Chrono carries a camera that looks down at the floor just ahead of it. It sees a patch of the latest picture, finds the line in it, and steers to follow the line.

The pictures come from one of two endpoints of the Pi's server:

Endpoint Pictures The robot
/odysseus/camera/square-path, the default generated, no camera needed. Every 5 s the picture shows the next side of a square follows each side, waits at its end and turns onto the next side when it appears
/odysseus/camera, with --pi-camera the Pi camera, looking down at a square drawn on paper follows the line around the square

Either way the loop runs live: the robot always sees the latest picture, so if the line moves while it drives, it sees the line where the line is now.

One lap of the square path of the Pi's server

One lap of the square path, from the Pi's server, at the speed it ran. The yellow line is the path of the axle centre; the robot's camera image is in the top left corner.

\[\text{Pi} \xrightarrow{\text{MJPEG over HTTP}} \text{floor} \xrightarrow{\text{robot pose}} \text{robot camera image} \xrightarrow{\text{line}} (v, \omega) \xrightarrow{\text{Chrono}} \text{new pose} \]

What you need

  • bitsim built with Chrono and an OpenCV that has FFmpeg, see Installing bitsim. OpenCV reads the camera stream with FFmpeg, and an OpenCV built without it gets no pictures. Ubuntu's libopencv-dev has FFmpeg; to use it, configure bitsim with -DOpenCV_DIR=/usr/lib/x86_64-linux-gnu/cmake/opencv4. The example checks this when it starts.
  • A Raspberry Pi 5 that runs the server, or, without a Pi, camera_server.py on the same computer; see bitsim_example_pi_camera_line_following_run.

For --pi-camera you also need

  • a camera module on the Pi, for example the Camera Module 3,
  • a sheet of paper with a square on it in thick dark lines. Black electrical tape works well. The line should be about 3 to 5 % of the picture's height wide, and the square should fill about half the picture,
  • a stand that holds the camera above the paper, looking straight down, so that it sees the whole square.

The pieces

Piece Where What it does
the Pi's server, or camera_server.py the Pi FastAPI app that streams the square path and the camera as MJPEG
MJPEG_HTTPCameraBackend bitsim receives the stream on a thread of its own and keeps the latest frame
FloorImage bitsim the picture as a floor: which pixel is at which point of the world
DownwardCamera bitsim the robot's camera: what it sees of a floor from a pose
CHRONO_DiffDriveRobot bitsim the robot, with its camera read from the robot file
find_square, find_segment, read_line, LineFollower pi_camera_line_following.cpp find the line, see it, steer
SquarePathDriver pi_camera_line_following.cpp drives the square path side by side

The server

The simulator uses the endpoints of the Odysseus robot's server. camera_server.py, in examples/pi_camera_line_following/pi_camera_server, has the same endpoints, so you can use it on a Pi of your own or on any computer:

Endpoint Gives
GET /odysseus/camera/square-path the square path: an MJPEG stream of one side of a square at a time
GET /odysseus/camera the camera: an MJPEG stream, a multipart/x-mixed-replace response of one JPEG after another
GET /odysseus/camera/frame the latest camera frame as one JPEG
GET /odysseus/camera/info the source, frame size and frame rate

The square path needs no camera. Its square is centred in the picture and half as high as the picture. Every --period seconds, 5 by default, the picture switches to the next side, going counterclockwise as seen from above: bottom, right, top, left. Only the current side is drawn.

For the camera, a thread of its own reads the camera and keeps the latest frame as JPEG. Each client of /odysseus/camera gets that frame whenever it changes, at most --fps times a second, 20 by default; a slow client skips frames instead of falling behind. On the Pi the frames come from Picamera2. With --synthetic the server draws a whole square on paper instead: slightly rotated, lit unevenly, noisy and drifting a little, so that the simulator does not get a perfect picture.

The floor

The picture covers a floor --floor-width metres wide, 3 m by default, centred on the world origin. A 640 x 480 picture makes the floor 3 m x 2.25 m, about 4.7 mm per pixel. The square of the square path is then 1.125 m long and the line 8.4 cm wide, a good size for a robot with its wheels 0.4 m apart.

The simulator uses the line in the pictures to start the robot and to measure how well the robot follows it; the robot itself sees only through its camera.

  • On the square path it waits until the picture switches to the next side, so that the robot starts with the whole period ahead of it. The side is the largest long, thin dark blob. The robot starts at its beginning, facing along it so that the centre of the picture is on its left. Each new side is added to the path as it appears.
  • With the camera it looks for the square in the first picture: the largest dark outline with a hole in it. Halfway between its outer and inner edges is the centre line. The robot starts in the middle of the bottom side, facing along it with the inside of the square on its left.

Either way the robot goes around counterclockwise.

The robot's camera

The robot file robots/bitsim_diff_drive_robot.json describes the camera:

Setting Value Meaning
type downward-camera a camera that looks straight down
offset 0.35 m how far ahead of the axle centre the middle of its view is
view_length 0.3 m how much floor it sees along the robot's heading
view_width 0.4 m and across it
image_width, image_height 160 x 120 the size of its image
update_rate 20 /s images per second

The top row of its image is the far edge of the view and column 0 is the robot's left, as a camera that faces forward and tilts down would show it. view turns the pose of the robot into an affine map from the camera's pixels to the floor's pixels and samples the picture with it, so it costs the same whatever the pose. to_robot goes the other way, from a pixel of the camera's image to metres ahead of and to the left of the robot.

Seeing the line

The paper is not equally bright everywhere, so a fixed threshold would not work under every lamp. The paper's brightness is taken as the level that 90 % of the pixels are darker than, and a pixel is line if it is darker than 0.6 times that. The middle of the line pixels, in robot coordinates, is \((f, l)\): \(f\) metres ahead and \(l\) metres to the left. If less than 1 % of the image is line, the camera has lost it.

Steering

The robot uses pure pursuit. It drives along the circle that starts where it is, heading the way it faces, and passes through \((f, l)\). That circle has the curvature

\[\kappa = \frac{2 l}{f^2 + l^2} \]

so with forward speed \(v\) the turn rate is \(\omega = v \kappa\). On a straight side the line is ahead, \(l \approx 0\), and the robot drives straight. It slows down as \(|l|\) grows, to 30 % of its cruise speed.

With the camera the corners of the square are in the picture. The camera sees the line bend away to the left, the middle of the line pixels moves left, \(l\) grows and the robot turns. Because the camera looks 0.35 m ahead, it starts to turn before its axle reaches the corner, so the axle centre cuts the corners by a few centimetres. If the camera loses the line the robot stops and turns towards where it last saw it. After 5 s without it, it gives up. The cruise speed is 0.25 m/s.

The square path

On the square path a corner is never in the picture: the line simply ends until the next side appears. Pure pursuit cannot see that coming, and turning on the spot where the line leaves the camera's view, 0.2 m short of the corner, would leave the next side to the side of the robot, out of its camera's view. But the robot knows one more thing: the path goes counterclockwise, so the next side always starts at the corner and leaves it to the left. The SquarePathDriver uses that:

  1. Follow the side with pure pursuit. Once the end of the side comes into view, the top row of line pixels is below the top of the image, it notes where the corner is: half a line width short of the end.
  2. To the corner: when the end has passed under the camera, it drives on to the corner by its own pose, slowing down as it gets close.
  3. Turn left on the spot until it faces at right angles to the side it followed. That is the side of the path nearest to it, not the latest one: if the robot is late, the next side may already be showing.
  4. Wait until its camera sees a line. The next side starts under the robot and runs straight ahead of it.

A side and its corner have to be done before the next side appears, here in 5 s. The side is 1.125 m long, so the robot drives at 0.35 m/s and turns at up to 1.5 rad/s: about 3.2 s for the side and 1 s for the turn. The turn overshoots by up to about 17 degrees, because the motors take a moment to stop, and the robot weaves a little as it settles onto the next side. If it is too slow, the next side appears before it has reached the corner. While it still sees the old side end it carries on to the corner; if the old side disappears before its end came into view, the robot cannot know where the corner is, and waits for a line it cannot see. After 15 s it gives up.

Real time

The picture is real, so the simulation keeps to real time: after each step it waits until the wall clock catches up. The robot takes a camera image every 50 ms of the latest frame. With the server on the same computer that frame is on average about 25 ms old; over WiFi from a Pi, expect more.

If the stream stops, for example when the Pi goes off the network, the robot stops. The backend opens the stream again every half second, and once frames arrive the robot drives on.

Running the example

Give the example the address of the server; --pi-camera switches from the square path to the camera:

./pi_camera_line_following --render http://raspberrypi.local:8000 # the square path
./pi_camera_line_following --render --pi-camera http://raspberrypi.local:8000 # the Pi camera

Use the Pi's IP address if its name does not resolve. --render opens a window with the picture, the line as the simulator knows it, the robot, what its camera sees, in the top left corner, and the path of its axle centre.

--record FILE writes the same picture to a video, 20 pictures for each second of the simulation, with or without --render. The movie above was made with

./pi_camera_line_following --record lap.avi
ffmpeg -i lap.avi -vf "fps=10,scale=560:-1:flags=lanczos,split[a][b];[a]palettegen=max_colors=64:stats_mode=diff[p];[b][p]paletteuse=dither=none:diff_mode=rectangle" -loop 0 pi_camera_line_following_lap.gif

To run camera_server.py on a Pi, install Picamera2 and OpenCV from Raspberry Pi OS, and FastAPI and uvicorn in a virtual environment that can also see them:

sudo apt install python3-picamera2 python3-opencv
python3 -m venv --system-site-packages ~/bitsim-camera
~/bitsim-camera/bin/pip install fastapi uvicorn
~/bitsim-camera/bin/python camera_server.py

Without a Pi, run it on the same computer. --synthetic makes /odysseus/camera draw a square instead of using a camera; the square path is always there:

pip install -r examples/pi_camera_line_following/pi_camera_server/requirements.txt
python3 examples/pi_camera_line_following/pi_camera_server/camera_server.py --synthetic
./pi_camera_line_following --render http://localhost:8000
./pi_camera_line_following --render --pi-camera http://localhost:8000

Output

On the square path of camera_server.py:

Pictures 640 x 480 pixels, the floor is 3.000 x 2.250 m
Side: 1.125 m long, line 0.084 m wide
Start at (0.565, -0.565) heading 90.000 deg
t [s] x [m] y [m] head [deg] line left [m] v [m/s] w [rad/s] off line [m] picture age [ms]
0.01 0.565 -0.565 90.0 0.0000 0.350 0.000 0.000 8
1.00 0.565 -0.295 90.0 0.0000 0.350 0.000 0.000 3
2.00 0.565 0.140 90.0 0.0000 0.350 0.000 0.000 49
3.01 0.565 0.500 90.0 lost 0.150 0.000 0.000 6
4.01 0.569 0.567 130.2 lost 0.000 1.425 0.008 1
5.01 0.607 0.564 -163.1 lost 0.000 0.000 0.042 46
6.01 0.511 0.559 176.7 0.0096 0.333 0.053 0.001 43
...
22.00 0.480 -0.516 42.0 0.1397 0.105 0.355 0.048 12
The robot went once around the square in 22.230 s of simulation, 22.228 s of wall time
Distance of the axle centre from the line: mean 0.023 m, largest 0.067 m (the line is 0.084 m wide)
Camera images: 445, without the line in them 105
Stream: 19.9 frames/s, mean age of the picture used 23.9 ms, reconnections 0

The robot started on the right side, which was the side that appeared while it waited. At 3 s the end of the side had passed under its camera, the line is lost, and it drove on to the corner and turned. By 6 s the top side had appeared and it followed it. Its axle centre was 2.3 cm from the line on average, and at most 6.7 cm, while it settled onto a side after a turn.

With --pi-camera and the synthetic camera:

The robot went once around the square in 34.660 s of simulation, 34.660 s of wall time
Distance of the axle centre from the line: mean 0.034 m, largest 0.117 m (the line is 0.085 m wide)
Camera images: 694, without the line in them 0
Stream: 20.0 frames/s, mean age of the picture used 24.3 ms, reconnections 0

The robot never lost the line. It cut the corners, as it turns before its axle reaches them.

Things to try

  1. Run the server with --period 4, then 3. At what period can the robot no longer keep up with the square path, and what does it do then?
  2. Move the paper slowly while the robot drives with --pi-camera. How fast can you move it before the robot loses the line?
  3. Change offset in the robot file to 0.2 m and to 0.5 m. How do the corners and the largest distance from the line change?
  4. Run the server with --fps 5. The robot sees the floor less often and later. What happens at the corners, and at what frame rate does it lose the line?
  5. Raise the cruise speed, CRUISE_SPEED in pi_camera_line_following.cpp. Pure pursuit with a fixed look ahead has a speed above which it cannot take a corner; find it.
  6. Draw a circle instead of a square. find_square will not find it; make the start work from any closed line.

The code

The simulator:

// A line following robot that sees through a Raspberry Pi camera
//
// A Raspberry Pi 5 streams pictures of a line drawn on paper over HTTP. Each
// picture is the floor of the simulated world. The differential drive robot of
// the chrono_diff_drive example carries a camera that looks down at the floor just ahead of it;
// it sees a patch of the latest picture, finds the line in it and steers to
// follow it.
//
// The pictures come from one of two endpoints of the Pi's server:
//
// /odysseus/camera/square-path (the default) generated pictures, no camera.
// Every few seconds the picture shows the next side of a square. The
// robot follows the side it sees, waits at its end, and turns onto the
// next side when it appears, so it drives around the square side by side
// /odysseus/camera (--pi-camera) the Pi camera, looking down at
// a square drawn on paper. The robot follows the line around it
//
// Usage: pi_camera_line_following [--pi-camera] [--render] [--record FILE] [--floor-width W]
// [server URL]
//
// --floor-width is how wide, in metres, the floor that a picture covers is;
// 3 by default. Without a Pi, run camera_server.py --synthetic on this
// computer and pass http://localhost:8000.
#include "bitsim/bitsim_config.h"
#include <chrono/physics/ChBodyEasy.h>
#include <chrono/physics/ChContactMaterialNSC.h>
#include <chrono/physics/ChSystemNSC.h>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <limits>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
{
using Point = std::array<real_t, 2>;
const std::string DEFAULT_SERVER = "http://alex-rpi-5.local:8000";
const std::string SQUARE_PATH_ENDPOINT = "/odysseus/camera/square-path";
const std::string CAMERA_ENDPOINT = "/odysseus/camera";
const std::string ROBOT_FILE = bitsim::consts::ROBOTS_DIR + "/bitsim_diff_drive_robot.json";
const std::string WINDOW_TITLE = "A line following robot with a Raspberry Pi camera";
const real_t STEP_SIZE = 0.01; // [s]
const real_t DEFAULT_FLOOR_WIDTH = 3.0; // [m]
const real_t TIME_LIMIT = 120.0; // [s]
const real_t PRINT_PERIOD = 1.0; // [s]
// The line follower
const real_t CRUISE_SPEED = 0.25; // [m/s]
const real_t MIN_SPEED_RATIO = 0.3; // of the cruise speed, in sharp turns
const real_t MAX_TURN_RATE = 1.5; // [rad/s]
const real_t SEARCH_TURN_RATE = 0.6; // [rad/s]
const real_t LOST_TIME = 5.0; // [s] with no line before giving up, Pi camera
const real_t WAIT_TIME = 15.0; // [s] to wait for the next side, square path
const real_t MIN_LINE_COVERAGE = 0.01; // of the camera image
// On the square path each side, with its corner, has to be done before the
// next side appears, so the robot drives faster there
const real_t SQUARE_PATH_SPEED = 0.35; // [m/s]
const real_t CORNER_TURN_RATE = 1.5; // [rad/s]
const real_t STOP_GAIN = 2.0; // [1/s] how quickly to slow down for the corner
const real_t DARK_RATIO = 0.6; // darker than this times the paper is line
// ---------------------------------------------------------------------------
// Seeing the line
// ---------------------------------------------------------------------------
cv::Mat to_gray(const cv::Mat &image)
{
if (image.channels() == 1)
{
return image;
}
cv::Mat gray;
cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
return gray;
}
// The pixels much darker than the paper. The paper is the brightness that
// 90 % of the pixels are darker than, so uneven lighting does not matter much
cv::Mat dark_pixels(const cv::Mat &gray)
{
std::vector<uchar> values(gray.begin<uchar>(), gray.end<uchar>());
auto paper = values.begin() + static_cast<long>(0.9 * (values.size() - 1));
std::nth_element(values.begin(), paper, values.end());
return gray < DARK_RATIO * (*paper);
}
// What the robot's camera makes of its image
{
bool found{false};
real_t forward{0.0}; // where the middle of the line it sees is: ahead of the axle [m]
real_t left{0.0}; // and to its left [m]
real_t coverage{0.0}; // the part of the image that is line
cv::Point2d pixel; // the middle of the line in the image
bool ends{false}; // whether the line ends inside the image, before its top
real_t end{0.0}; // how far ahead of the axle the far end of the line is [m]
};
LineReading read_line(const cv::Mat &view, const DownwardCamera &camera)
{
const cv::Mat dark = dark_pixels(to_gray(view));
const cv::Moments m = cv::moments(dark, true);
LineReading reading;
reading.coverage = m.m00 / static_cast<real_t>(dark.total());
if (reading.coverage < MIN_LINE_COVERAGE)
{
return reading;
}
reading.found = true;
reading.pixel = cv::Point2d(m.m10 / m.m00, m.m01 / m.m00);
const auto where = camera.to_robot(reading.pixel.x, reading.pixel.y);
reading.forward = where[0];
reading.left = where[1];
// The far end of the line is its top row in the image
int top = 0;
while (top < dark.rows && cv::countNonZero(dark.row(top)) == 0)
{
++top;
}
reading.ends = top > 2;
reading.end = camera.to_robot(reading.pixel.x, top)[0];
return reading;
}
// ---------------------------------------------------------------------------
// The line on the paper
// ---------------------------------------------------------------------------
// A straight stretch of the centre of the line, in world coordinates
struct Segment
{
Point middle() const { return {0.5 * (a[0] + b[0]), 0.5 * (a[1] + b[1])}; }
real_t length() const { return std::hypot(b[0] - a[0], b[1] - a[1]); }
real_t distance(const Point &p) const
{
const real_t dx = b[0] - a[0];
const real_t dy = b[1] - a[1];
const real_t s =
std::clamp(((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / (dx * dx + dy * dy), 0.0, 1.0);
return std::hypot(p[0] - a[0] - s * dx, p[1] - a[1] - s * dy);
}
};
// The line the robot should follow, as far as the simulator knows it: the
// whole square with the Pi camera, the sides seen so far on the square path.
// It is used to start the robot and to measure how well it follows the line;
// the robot itself sees only through its camera
struct Path
{
std::vector<Segment> segments;
Point centre{0.0, 0.0};
real_t distance(const Point &p) const
{
real_t best = std::numeric_limits<real_t>::max();
for (const auto &segment : segments)
{
best = std::min(best, segment.distance(p));
}
return best;
}
// Add a side, unless it is one already known
void add(const Segment &segment)
{
for (const auto &known : segments)
{
const Point m = segment.middle();
const Point k = known.middle();
if (std::hypot(m[0] - k[0], m[1] - k[1]) < 0.5 * line_width + 0.05)
{
return;
}
}
segments.push_back(segment);
}
};
// Find the square: the largest dark outline with a hole in it. The centre
// line is halfway between its outer and inner edges. Its sides go
// counterclockwise
std::optional<Path> find_square(const FloorImage &floor)
{
cv::Mat dark = dark_pixels(to_gray(floor.image()));
cv::morphologyEx(dark, dark, cv::MORPH_CLOSE,
cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 5)));
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(dark, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE);
int outer = -1;
int inner = -1;
double outer_area = 0.0;
for (int i = 0; i < static_cast<int>(contours.size()); ++i)
{
const bool is_outline = hierarchy[i][3] < 0 && hierarchy[i][2] >= 0;
const double area = cv::contourArea(contours[i]);
if (!is_outline || area <= outer_area)
{
continue;
}
// Its largest hole
int hole = -1;
double hole_area = 0.0;
for (int child = hierarchy[i][2]; child >= 0; child = hierarchy[child][0])
{
const double a = cv::contourArea(contours[child]);
if (a > hole_area)
{
hole = child;
hole_area = a;
}
}
if (hole >= 0 && hole_area > 0.3 * area)
{
outer = i;
inner = hole;
outer_area = area;
}
}
if (outer < 0 || outer_area < 0.02 * static_cast<double>(dark.total()))
{
return std::nullopt;
}
const cv::RotatedRect a = cv::minAreaRect(contours[outer]);
const cv::RotatedRect b = cv::minAreaRect(contours[inner]);
const cv::RotatedRect centre_line(
(a.center + b.center) * 0.5,
cv::Size2f((a.size.width + b.size.width) * 0.5f, (a.size.height + b.size.height) * 0.5f),
a.angle);
const real_t aspect = centre_line.size.width / centre_line.size.height;
if (aspect < 0.75 || aspect > 1.33)
{
return std::nullopt;
}
cv::Point2f pixels[4];
centre_line.points(pixels);
Path square;
square.centre = floor.to_world(cv::Point2d(centre_line.center));
std::array<std::pair<real_t, Point>, 4> by_angle;
for (uint_t i = 0; i < 4; ++i)
{
const Point p = floor.to_world(cv::Point2d(pixels[i]));
by_angle[i] = {std::atan2(p[1] - square.centre[1], p[0] - square.centre[0]), p};
}
std::sort(by_angle.begin(), by_angle.end(),
[](const auto &l, const auto &r) { return l.first < r.first; });
for (uint_t i = 0; i < 4; ++i)
{
square.segments.push_back({by_angle[i].second, by_angle[(i + 1) % 4].second});
}
square.line_width = 0.25 * ((a.size.width - b.size.width) + (a.size.height - b.size.height)) *
floor.metres_per_pixel();
return square;
}
// Find a single straight line: the largest dark blob that is long and thin.
// Its ends are where the centre of the line ends, inside its rounded caps
std::optional<std::pair<Segment, real_t>> find_segment(const FloorImage &floor)
{
const cv::Mat dark = dark_pixels(to_gray(floor.image()));
std::vector<std::vector<cv::Point>> contours;
cv::findContours(dark, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
const std::vector<cv::Point> *largest = nullptr;
double largest_area = 0.0;
for (const auto &contour : contours)
{
const double area = cv::contourArea(contour);
if (area > largest_area)
{
largest = &contour;
largest_area = area;
}
}
if (!largest || largest_area < 0.002 * static_cast<double>(dark.total()))
{
return std::nullopt;
}
const cv::RotatedRect rect = cv::minAreaRect(*largest);
const real_t length = std::max(rect.size.width, rect.size.height);
const real_t width = std::min(rect.size.width, rect.size.height);
if (length < 4.0 * width)
{
return std::nullopt;
}
// The direction of the long side of the rectangle
const real_t angle =
(rect.size.width >= rect.size.height ? rect.angle : rect.angle + 90.0) * PI / 180.0;
const cv::Point2d along(std::cos(angle), std::sin(angle));
const cv::Point2d centre(rect.center);
const real_t half = 0.5 * (length - width);
const Segment segment{floor.to_world(centre - half * along),
floor.to_world(centre + half * along)};
return std::make_pair(segment, width * floor.metres_per_pixel());
}
// The direction of the side of a path nearest to a point: the side a robot
// there is following. It need not be the latest side; the next one can appear
// before the robot reaches the end of the one it is on
real_t nearest_side_heading(const Path &path, const Point &p)
{
const Segment *nearest = &path.segments.front();
for (const auto &segment : path.segments)
{
if (segment.distance(p) < nearest->distance(p))
{
nearest = &segment;
}
}
return std::atan2(nearest->b[1] - nearest->a[1], nearest->b[0] - nearest->a[0]);
}
// Where the robot starts, and which way it faces
struct Start
{
};
// With the Pi camera: the middle of the bottom side of the square, facing
// along it so that the inside of the square is on its left
Start start_on_square(const Path &square)
{
const Segment *bottom = &square.segments.front();
for (const auto &segment : square.segments)
{
if (segment.middle()[1] < bottom->middle()[1])
{
bottom = &segment;
}
}
const Point m = bottom->middle();
return {m[0], m[1], std::atan2(bottom->b[1] - bottom->a[1], bottom->b[0] - bottom->a[0])};
}
// On the square path: the side goes counterclockwise around the centre of the
// picture, so the centre is on the left of a robot that drives along it. Turn
// the side that way round and start at its beginning
Segment counterclockwise(const Segment &side, const Point &centre)
{
const real_t dx = side.b[0] - side.a[0];
const real_t dy = side.b[1] - side.a[1];
const Point m = side.middle();
const real_t cross = dx * (centre[1] - m[1]) - dy * (centre[0] - m[0]);
return cross >= 0.0 ? side : Segment{side.b, side.a};
}
{
return {side.a[0], side.a[1], std::atan2(side.b[1] - side.a[1], side.b[0] - side.a[0])};
}
// ---------------------------------------------------------------------------
// The line follower
// ---------------------------------------------------------------------------
struct Command
{
real_t v{0.0};
real_t omega{0.0};
};
// Pure pursuit: drive along the circle through the middle of the line the
// camera sees. In a corner the line bends away, its middle moves sideways and
// the robot turns. Slow down in sharp turns.
//
// When the camera loses the line, the robot either turns towards where it last
// saw it, to look for it, or stops and waits for the line to come back. On the
// square path the line ends at each corner until the next side appears, so
// there it waits
{
public:
enum class WhenLost
{
};
LineFollower(real_t half_view_width, real_t cruise_speed, WhenLost when_lost,
: half_view_width_(half_view_width), cruise_speed_(cruise_speed), when_lost_(when_lost),
give_up_after_(give_up_after)
{
}
Command command(const LineReading &line, real_t dt)
{
if (!line.found)
{
lost_for_ += dt;
if (when_lost_ == WhenLost::WAIT)
{
return {};
}
return {0.0, last_left_ >= 0.0 ? SEARCH_TURN_RATE : -SEARCH_TURN_RATE};
}
lost_for_ = 0.0;
last_left_ = line.left;
const real_t curvature =
2.0 * line.left / (line.forward * line.forward + line.left * line.left);
const real_t sideways = std::min(std::abs(line.left) / half_view_width_, 1.0);
const real_t v = cruise_speed_ * std::max(1.0 - sideways, MIN_SPEED_RATIO);
return {v, std::clamp(v * curvature, -MAX_TURN_RATE, MAX_TURN_RATE)};
}
bool has_given_up() const { return lost_for_ > give_up_after_; }
real_t give_up_after() const { return give_up_after_; }
private:
real_t half_view_width_;
real_t cruise_speed_;
WhenLost when_lost_;
real_t give_up_after_;
real_t last_left_{0.0};
real_t lost_for_{0.0};
};
// On the square path the line ends at every corner until the next side
// appears, to the left: the path goes counterclockwise. So the robot follows
// the side it sees and, once the end of the side comes into view, remembers
// where the corner is. When the end has passed under the camera it drives on
// to the corner by its own pose, turns left by a quarter turn and waits. The
// next side then starts under the robot and runs straight ahead of it
{
public:
enum class State
{
};
SquarePathDriver(LineFollower follower, real_t near_edge, real_t half_line_width)
: follower_(follower), near_edge_(near_edge), half_line_width_(half_line_width)
{
}
// side_heading is the direction of the side the robot is on
Command command(const LineReading &line, const Point &position, real_t heading,
real_t side_heading, real_t dt)
{
const Point ahead{std::cos(heading), std::sin(heading)};
switch (state_)
{
if (line.found)
{
followed_heading_ = side_heading;
}
if (line.found && line.ends)
{
// The corner is half a line width short of the end of the line
const real_t to_corner = line.end - half_line_width_;
corner_ =
Point{position[0] + to_corner * ahead[0], position[1] + to_corner * ahead[1]};
}
if (corner_ && (!line.found || line.end < near_edge_ + half_line_width_))
{
state_ = State::TO_CORNER;
break;
}
return follower_.command(line, dt);
{
const real_t remaining =
((*corner_)[0] - position[0]) * ahead[0] + ((*corner_)[1] - position[1]) * ahead[1];
if (remaining > 0.01)
{
return {std::clamp(STOP_GAIN * remaining, 0.05, SQUARE_PATH_SPEED), 0.0};
}
// The next side leaves the corner at right angles to the side the
// robot followed, whichever way the robot happens to face
turn_to_ = followed_heading_ + 0.5 * PI;
state_ = State::TURN;
break;
}
if (std::abs(std::remainder(turn_to_ - heading, 2.0 * PI)) > 0.03)
{
const real_t error = std::remainder(turn_to_ - heading, 2.0 * PI);
// Ease off near the heading: the motors take a moment to stop
return {0.0, std::clamp(1.5 * error, -CORNER_TURN_RATE, CORNER_TURN_RATE)};
}
state_ = State::WAIT;
break;
break;
}
if (state_ == State::WAIT)
{
if (line.found)
{
corner_.reset();
state_ = State::FOLLOW;
return follower_.command(line, dt);
}
waited_ += dt;
return {};
}
return command(line, position, heading, side_heading, dt);
}
State state() const noexcept { return state_; }
bool has_given_up() const { return follower_.has_given_up() || waited_ > WAIT_TIME; }
real_t give_up_after() const { return WAIT_TIME; }
private:
LineFollower follower_;
real_t near_edge_;
real_t half_line_width_;
std::optional<Point> corner_;
real_t turn_to_{0.0};
real_t followed_heading_{0.0};
real_t waited_{0.0};
};
// ---------------------------------------------------------------------------
// The simulated world
// ---------------------------------------------------------------------------
class World
{
public:
explicit World(const Start &start)
{
system_.SetGravitationalAcceleration(
chrono::ChVector3d(0.0, 0.0, -bitsim::consts::maths::G));
system_.SetCollisionSystemType(chrono::ChCollisionSystem::Type::BULLET);
// The camera runs in real time, so the solver has to be quick
system_.SetSolverType(chrono::ChSolver::Type::BARZILAIBORWEIN);
system_.GetSolver()->AsIterative()->SetMaxIterations(40);
auto material = chrono_types::make_shared<chrono::ChContactMaterialNSC>();
material->SetFriction(0.8f);
material->SetRestitution(0.1f);
auto ground = chrono_types::make_shared<chrono::ChBodyEasyBox>(20.0, 20.0, 0.1, 1000.0,
false, true, material);
ground->SetPos(chrono::ChVector3d(0.0, 0.0, -0.05));
ground->SetFixed(true);
system_.Add(ground);
robot_.load(std::filesystem::path(ROBOT_FILE));
if (!robot_.get_camera())
{
throw std::runtime_error("The robot file " + ROBOT_FILE + " has no front-camera");
}
robot_.set_world_pose(start.x, start.y, start.yaw);
robot_.add_to_sys(system_);
}
void step(const Command &command)
{
robot_.set_velocity(command.v, command.omega);
robot_.update(STEP_SIZE);
system_.DoStepDynamics(STEP_SIZE);
}
real_t time() const { return system_.GetChTime(); }
Point position() const { return {robot_.axle_center().x(), robot_.axle_center().y()}; }
real_t heading() const { return robot_.heading(); }
const CHRONO_DiffDriveRobot &robot() const { return robot_; }
private:
chrono::ChSystemNSC system_;
CHRONO_DiffDriveRobot robot_;
};
// ---------------------------------------------------------------------------
// The picture
// ---------------------------------------------------------------------------
class Display
{
public:
// Shows the picture in a window if show_window, and writes it to the video
// file record if that is not empty, frame_rate pictures a second
Display(const FloorImage &floor, bool show_window, const std::string &record, real_t frame_rate)
: show_window_(show_window), record_(record), frame_rate_(frame_rate)
{
scale_ = std::min(1.0, 900.0 / floor.image().cols);
if (show_window_)
{
cv::namedWindow(WINDOW_TITLE, cv::WINDOW_AUTOSIZE);
}
}
// Returns false once the window is closed or Esc is pressed
bool show(const FloorImage &floor, const World &world, const cv::Mat &view,
const LineReading &line, const Path &path, const std::vector<Point> &trail,
const std::string &text)
{
cv::Mat picture;
cv::resize(floor.image(), picture, cv::Size(), scale_, scale_, cv::INTER_AREA);
if (picture.channels() == 1)
{
cv::cvtColor(picture, picture, cv::COLOR_GRAY2BGR);
}
auto pixel = [&](const Point &p)
{
const auto px = floor.to_pixel(p[0], p[1]);
return cv::Point(static_cast<int>(std::round(px.x * scale_)),
static_cast<int>(std::round(px.y * scale_)));
};
auto polygon = [&](const auto &points, const cv::Scalar &colour, int width)
{
std::vector<cv::Point> pts;
for (const auto &p : points)
{
pts.push_back(pixel(p));
}
cv::polylines(picture, pts, true, colour, width, cv::LINE_AA);
};
// The line as the simulator knows it, and where the robot went
for (const auto &segment : path.segments)
{
cv::line(picture, pixel(segment.a), pixel(segment.b), cv::Scalar(80, 180, 80), 1,
cv::LINE_AA);
}
for (std::size_t i = 1; i < trail.size(); ++i)
{
cv::line(picture, pixel(trail[i - 1]), pixel(trail[i]), cv::Scalar(0, 200, 255), 2,
cv::LINE_AA);
}
// The robot: chassis, wheels and what its camera sees
const auto &robot = world.robot();
const auto &data = robot.get_data();
const Point c = world.position();
const real_t yaw = world.heading();
auto body = [&](real_t forward, real_t left) -> Point
{
return {c[0] + forward * std::cos(yaw) - left * std::sin(yaw),
c[1] + forward * std::sin(yaw) + left * std::cos(yaw)};
};
const real_t r = data.wheel_radius;
const real_t half_axle = 0.5 * data.axle_length;
polygon(std::array<Point, 4>{body(0.35, 0.15), body(0.35, -0.15), body(-0.15, -0.15),
body(-0.15, 0.15)},
cv::Scalar(230, 160, 90), 2);
for (const real_t side : {half_axle, -half_axle})
{
cv::line(picture, pixel(body(-r, side)), pixel(body(r, side)), cv::Scalar(60, 60, 60),
4, cv::LINE_AA);
}
const auto &camera = *robot.get_camera();
const auto footprint = camera.footprint(c[0], c[1], yaw);
polygon(footprint, cv::Scalar(220, 200, 0), 1);
if (line.found)
{
cv::circle(picture, pixel(body(line.forward, line.left)), 4, cv::Scalar(0, 0, 255),
cv::FILLED, cv::LINE_AA);
}
// The camera's image in the top left corner
// At its own size it fits beside the square, which is centred
cv::Mat inset = view.clone();
if (inset.channels() == 1)
{
cv::cvtColor(inset, inset, cv::COLOR_GRAY2BGR);
}
if (line.found)
{
cv::circle(inset, line.pixel, 4, cv::Scalar(0, 0, 255), cv::FILLED, cv::LINE_AA);
}
cv::rectangle(inset, cv::Rect(0, 0, inset.cols, inset.rows), cv::Scalar(220, 200, 0), 2);
if (inset.cols + 10 < picture.cols && inset.rows + 40 < picture.rows)
{
inset.copyTo(picture(cv::Rect(10, 10, inset.cols, inset.rows)));
cv::putText(picture, "robot camera", cv::Point(12, inset.rows + 28),
cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(40, 40, 40), 1, cv::LINE_AA);
}
// The numbers along the bottom
cv::rectangle(picture, cv::Rect(0, picture.rows - 28, picture.cols, 28),
cv::Scalar(250, 250, 250), cv::FILLED);
cv::putText(picture, text, cv::Point(8, picture.rows - 9), cv::FONT_HERSHEY_SIMPLEX, 0.5,
cv::Scalar(30, 30, 30), 1, cv::LINE_AA);
// One picture every 1 / frame_rate_ s of simulation, so the video
// plays at the speed of the simulation
if (!record_.empty() && world.time() + 1e-9 >= next_record_)
{
next_record_ += 1.0 / frame_rate_;
if (!writer_.isOpened())
{
// MJPG in an .avi file needs no codec beyond OpenCV's own
const int codec = cv::VideoWriter::fourcc('M', 'J', 'P', 'G');
if (!writer_.open(record_, codec, frame_rate_, picture.size()))
{
throw std::runtime_error("Cannot write the video " + record_);
}
}
writer_.write(picture);
}
if (!show_window_)
{
return true;
}
cv::imshow(WINDOW_TITLE, picture);
const int key = cv::waitKey(1);
// The window is only visible a little after the first imshow, so it
// counts as closed once it has been visible and is not any more
const bool visible = cv::getWindowProperty(WINDOW_TITLE, cv::WND_PROP_VISIBLE) >= 1.0;
was_visible_ = was_visible_ || visible;
return key != 27 && (visible || !was_visible_);
}
private:
bool show_window_;
std::string record_;
real_t frame_rate_;
cv::VideoWriter writer_;
real_t next_record_{0.0};
bool was_visible_{false};
real_t scale_{1.0};
};
// ---------------------------------------------------------------------------
// Running it
// ---------------------------------------------------------------------------
struct Options
{
std::string server{DEFAULT_SERVER};
bool pi_camera{false};
bool render{false};
std::string record;
std::string url() const
{
}
};
Options parse(int argc, char **argv)
{
Options options;
for (int i = 1; i < argc; ++i)
{
const std::string arg = argv[i];
if (arg == "--render")
{
options.render = true;
}
else if (arg == "--pi-camera")
{
options.pi_camera = true;
}
else if (arg == "--record" && i + 1 < argc)
{
options.record = argv[++i];
}
else if (arg == "--floor-width" && i + 1 < argc)
{
options.floor_width = std::stod(argv[++i]);
}
else if (arg == "--help" || arg == "-h" || arg.rfind("--", 0) == 0)
{
std::cout << "Usage: pi_camera_line_following [--pi-camera] [--render] [--record FILE] "
"[--floor-width W] "
"[server URL]\n"
<< " Follows the square path of " << SQUARE_PATH_ENDPOINT
<< ", or with --pi-camera\n the Pi camera at " << CAMERA_ENDPOINT
<< ". The default server is " << DEFAULT_SERVER
<< ",\n the default floor width " << DEFAULT_FLOOR_WIDTH << " m"
<< std::endl;
std::exit(arg == "--help" || arg == "-h" ? 0 : 1);
}
else
{
options.server = arg;
while (!options.server.empty() && options.server.back() == '/')
{
options.server.pop_back();
}
}
}
return options;
}
// On the square path, wait until the picture switches to the next side, so
// that the robot starts at the beginning of a side with all of its time ahead
std::optional<std::pair<Segment, real_t>> wait_for_next_side(const MJPEG_HTTPCameraBackend &stream,
real_t floor_width, real_t timeout)
{
std::optional<Point> first;
const auto start = std::chrono::steady_clock::now();
uint_t last_index = 0;
while (milliseconds_since(start) < 1000.0 * timeout)
{
const auto frame = stream.latest_frame();
if (frame && frame->index != last_index)
{
last_index = frame->index;
if (const auto side = find_segment(FloorImage(frame->image, floor_width)))
{
const Point m = side->first.middle();
if (!first)
{
first = m;
}
else if (std::hypot(m[0] - (*first)[0], m[1] - (*first)[1]) > 0.1)
{
return side;
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
return std::nullopt;
}
int run(const Options &options)
{
{
std::cerr << "This OpenCV " << CV_VERSION
<< " was built without FFmpeg, so it cannot read the camera stream.\n"
<< "Build bitsim with an OpenCV that has FFmpeg, for example Ubuntu's:\n"
<< " cmake -DOpenCV_DIR=/usr/lib/x86_64-linux-gnu/cmake/opencv4 ..\n"
<< "or build OpenCV with -DWITH_FFMPEG=ON" << std::endl;
return 1;
}
config.url = options.url();
MJPEG_HTTPCameraBackend stream(config);
stream.connect();
std::cout << "Waiting for pictures from " << config.url << " ..." << std::endl;
if (!stream.wait_for_frame(15.0))
{
std::cerr << "No pictures from " << config.url << ". Is the server running?\n"
<< "Without a Pi, start camera_server.py --synthetic and pass "
"http://localhost:8000"
<< std::endl;
return 1;
}
CameraFrame frame = *stream.latest_frame();
FloorImage floor(frame.image, options.floor_width);
std::cout << std::fixed << std::setprecision(3) << "Pictures " << frame.image.cols << " x "
<< frame.image.rows << " pixels, the floor is " << floor.width() << " x "
<< floor.height() << " m\n";
// Find the line and where to start on it
Path path;
if (options.pi_camera)
{
const auto square = find_square(floor);
if (!square)
{
std::cerr << "There is no square in the camera's picture. Draw one with thick dark "
"lines and make sure the camera sees all of it"
<< std::endl;
return 1;
}
path = *square;
std::cout << "Square: side " << path.segments.front().length() << " m, line "
<< path.line_width << " m wide, centre (" << path.centre[0] << ", "
<< path.centre[1] << ")\n";
}
else
{
std::cout << "Waiting for the next side of the square path ..." << std::endl;
const auto side = wait_for_next_side(stream, options.floor_width, WAIT_TIME);
if (!side)
{
std::cerr << "The pictures do not show a side of a square that changes. Is "
<< config.url << " the square path?" << std::endl;
return 1;
}
frame = *stream.latest_frame();
floor = FloorImage(frame.image, options.floor_width);
path.line_width = side->second;
const Segment first = counterclockwise(side->first, path.centre);
path.add(first);
start = start_on_side(first);
std::cout << "Side: " << first.length() << " m long, line " << path.line_width
<< " m wide\n";
}
World world(start);
const auto &camera = *world.robot().get_camera();
const real_t half_view_width = 0.5 * camera.config().view_width;
LineFollower follower(half_view_width, options.pi_camera ? CRUISE_SPEED : SQUARE_PATH_SPEED,
options.pi_camera ? LineFollower::WhenLost::SEARCH
options.pi_camera ? LOST_TIME : WAIT_TIME);
const real_t near_edge = camera.config().offset - 0.5 * camera.config().view_length;
SquarePathDriver driver(follower, near_edge, 0.5 * path.line_width);
std::optional<Display> display;
if (options.render || !options.record.empty())
{
display.emplace(floor, options.render, options.record, camera.config().update_rate);
}
std::cout << "Start at (" << start.x << ", " << start.y << ") heading "
<< start.yaw * 180.0 / PI << " deg\n\n"
<< " t [s] x [m] y [m] head [deg] line left [m] v [m/s] w [rad/s]"
" off line [m] picture age [ms]\n";
const real_t camera_period = 1.0 / camera.config().update_rate;
real_t next_image = 0.0;
real_t next_print = 0.0;
cv::Mat view;
std::vector<Point> trail;
// Progress around the centre of the square, and how far from the line the
// robot drives
real_t last_angle = std::atan2(start.y - path.centre[1], start.x - path.centre[0]);
real_t travelled_angle = 0.0;
real_t error_sum = 0.0;
real_t max_error = 0.0;
uint_t n_errors = 0;
uint_t n_images = 0;
uint_t n_lost_images = 0;
real_t frame_age_sum = 0.0;
real_t frame_age = 0.0; // of the picture in the latest camera image [ms]
bool completed = false;
bool stopped = false;
const auto wall_start = std::chrono::steady_clock::now();
while (world.time() < TIME_LIMIT)
{
// The camera takes an image of the latest picture of the floor
if (world.time() >= next_image)
{
next_image += camera_period;
if (const auto latest = stream.latest_frame(); latest && latest->index != frame.index)
{
frame = *latest;
floor = FloorImage(frame.image, options.floor_width);
// On the square path, remember each side as it appears
if (!options.pi_camera)
{
if (const auto side = find_segment(floor))
{
path.add(counterclockwise(side->first, path.centre));
}
}
}
frame_age = milliseconds_since(frame.received_at);
frame_age_sum += frame_age;
view = world.robot().camera_view(floor);
line = read_line(view, camera);
options.pi_camera
? follower.command(line, camera_period)
: driver.command(line, world.position(), world.heading(),
nearest_side_heading(path, world.position()), camera_period);
++n_images;
n_lost_images += line.found ? 0 : 1;
if (options.pi_camera ? follower.has_given_up() : driver.has_given_up())
{
std::cout << "\nThe robot saw no line for "
<< (options.pi_camera ? follower.give_up_after() : driver.give_up_after())
<< " s and stops" << std::endl;
break;
}
if (!stream.is_alive())
{
}
}
world.step(command);
const Point p = world.position();
const real_t angle = std::atan2(p[1] - path.centre[1], p[0] - path.centre[0]);
travelled_angle += std::remainder(angle - last_angle, 2.0 * PI);
last_angle = angle;
const real_t error = path.distance(p);
error_sum += error;
max_error = std::max(max_error, error);
++n_errors;
if (trail.empty() || std::hypot(p[0] - trail.back()[0], p[1] - trail.back()[1]) > 0.01)
{
trail.push_back(p);
}
if (world.time() >= next_print)
{
next_print += PRINT_PERIOD;
std::cout << std::setw(9) << std::setprecision(2) << world.time()
<< std::setprecision(3) << std::setw(8) << p[0] << std::setw(8) << p[1]
<< std::setw(12) << std::setprecision(1) << world.heading() * 180.0 / PI
<< std::setprecision(3) << std::setw(15)
<< (line.found ? std::to_string(line.left).substr(0, 6) : "lost")
<< std::setw(9) << command.v << std::setw(11) << command.omega
<< std::setw(14) << error << std::setw(18) << std::setprecision(0)
<< frame_age << std::setprecision(3) << std::endl;
}
if (display && world.time() + 1e-9 >= next_image)
{
std::ostringstream text;
text << std::fixed << std::setprecision(1) << "t " << world.time() << " s lap "
<< 100.0 * std::clamp(travelled_angle / (2.0 * PI), 0.0, 1.0) << " % v "
<< std::setprecision(2) << command.v << " m/s off line " << error
<< " m stream " << std::setprecision(0) << stream.frame_rate() << " fps";
if (!display->show(floor, world, view, line, path, trail, text.str()))
{
stopped = true;
break;
}
}
if (travelled_angle >= 2.0 * PI)
{
completed = true;
break;
}
// The pictures arrive in real time, so the simulation keeps to real time
const real_t ahead =
world.time() -
std::chrono::duration<real_t>(std::chrono::steady_clock::now() - wall_start).count();
if (ahead > 0.0)
{
std::this_thread::sleep_for(std::chrono::duration<real_t>(ahead));
}
}
const real_t wall_time =
std::chrono::duration<real_t>(std::chrono::steady_clock::now() - wall_start).count();
std::cout << std::setprecision(3) << "\n"
<< (completed ? "The robot went once around the square"
: stopped ? "Stopped"
: "The robot did not get around the square")
<< " in " << world.time() << " s of simulation, " << wall_time << " s of wall time\n"
<< "Distance of the axle centre from the line: mean " << error_sum / n_errors
<< " m, largest " << max_error << " m (the line is " << path.line_width
<< " m wide)\n"
<< "Camera images: " << n_images << ", without the line in them " << n_lost_images
<< "\n"
<< "Stream: " << std::setprecision(1) << stream.frame_rate()
<< " frames/s, mean age of the picture used " << frame_age_sum / n_images
<< " ms, reconnections " << stream.n_reconnects() << std::endl;
stream.disconnect();
return completed ? 0 : 1;
}
} // namespace pi_camera_line_following
int main(int argc, char **argv)
{
try
{
}
catch (const std::exception &e)
{
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
A differential-drive robot in Chrono: a chassis, two driven wheels and a ball caster....
Definition diff_drive_robot.h:52
A camera on a robot that looks straight down at the floor ahead.
Definition downward_camera.h:112
An image of the floor, centred on the world origin.
Definition downward_camera.h:31
Receives the frames of an MJPEG stream over HTTP, the multipart/x-mixed-replace response that many ca...
Definition mjpeg_http_camera_backend.h:32
Definition pi_camera_line_following.cpp:630
bool show(const FloorImage &floor, const World &world, const cv::Mat &view, const LineReading &line, const Path &path, const std::vector< Point > &trail, const std::string &text)
Definition pi_camera_line_following.cpp:645
Display(const FloorImage &floor, bool show_window, const std::string &record, real_t frame_rate)
Definition pi_camera_line_following.cpp:634
Definition pi_camera_line_following.cpp:420
WhenLost
Definition pi_camera_line_following.cpp:423
@ SEARCH
Definition pi_camera_line_following.cpp:424
@ WAIT
Definition pi_camera_line_following.cpp:425
bool has_given_up() const
Definition pi_camera_line_following.cpp:456
Command command(const LineReading &line, real_t dt)
Definition pi_camera_line_following.cpp:435
LineFollower(real_t half_view_width, real_t cruise_speed, WhenLost when_lost, real_t give_up_after)
Definition pi_camera_line_following.cpp:428
real_t give_up_after() const
Definition pi_camera_line_following.cpp:457
static bool can_read_streams()
Whether this OpenCV can read HTTP streams at all. The backend reads them with OpenCV's FFmpeg backend...
Definition mjpeg_http_camera_backend.cpp:32
Definition pi_camera_line_following.cpp:475
State state() const noexcept
Definition pi_camera_line_following.cpp:559
real_t give_up_after() const
Definition pi_camera_line_following.cpp:561
bool has_given_up() const
Definition pi_camera_line_following.cpp:560
SquarePathDriver(LineFollower follower, real_t near_edge, real_t half_line_width)
Definition pi_camera_line_following.cpp:485
Command command(const LineReading &line, const Point &position, real_t heading, real_t side_heading, real_t dt)
Definition pi_camera_line_following.cpp:491
State
Definition pi_camera_line_following.cpp:478
@ TURN
Definition pi_camera_line_following.cpp:481
@ FOLLOW
Definition pi_camera_line_following.cpp:479
@ WAIT
Definition pi_camera_line_following.cpp:482
@ TO_CORNER
Definition pi_camera_line_following.cpp:480
Definition pi_camera_line_following.cpp:579
const CHRONO_DiffDriveRobot & robot() const
Definition pi_camera_line_following.cpp:618
World(const Start &start)
Definition pi_camera_line_following.cpp:581
real_t time() const
Definition pi_camera_line_following.cpp:615
Point position() const
Definition pi_camera_line_following.cpp:616
real_t heading() const
Definition pi_camera_line_following.cpp:617
void step(const Command &command)
Definition pi_camera_line_following.cpp:608
int main()
Definition discounted_returns.cpp:19
void points()
Definition basic_types.cpp:65
const real_t G
Acceleration due to gravity m/secs.
Definition bitsim_consts.h:68
const real_t PI
The PI constant.
Definition bitsim_consts.h:63
const std::string ROBOTS_DIR
Path to robots definitions.
Definition bitsim_consts.h:42
real_t milliseconds_since(WallClock::time_point t)
The milliseconds since a time point.
Definition timing.h:32
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
CartPoleState start()
Definition cart_pole_lqr_mpc.cpp:73
void record(const std::vector< Run > &runs, const std::string &directory)
Definition cart_pole_lqr_mpc.cpp:194
std::map< std::string, std::any > command(real_t v, real_t w)
Definition diff_drive_kinematics.cpp:29
real_t error(const Pose &a, const Pose &b)
Definition ekf_slam.cpp:176
where(plane)
Definition grid_world_gif.py:37
bitsim::control::DiffDriveCommand Command
Definition mcts_line_following.cpp:68
frame(fig)
Definition multi_agent_gif.py:29
Definition pi_camera_line_following.cpp:58
real_t milliseconds_since(WallClock::time_point t)
The milliseconds since a time point.
Definition timing.h:32
const real_t WAIT_TIME
Definition pi_camera_line_following.cpp:87
LineReading read_line(const cv::Mat &view, const DownwardCamera &camera)
Definition pi_camera_line_following.cpp:134
const real_t MIN_LINE_COVERAGE
Definition pi_camera_line_following.cpp:88
const real_t MIN_SPEED_RATIO
Definition pi_camera_line_following.cpp:83
Options parse(int argc, char **argv)
Definition pi_camera_line_following.cpp:796
Segment counterclockwise(const Segment &side, const Point &centre)
Definition pi_camera_line_following.cpp:387
const std::string CAMERA_ENDPOINT
Definition pi_camera_line_following.cpp:71
const real_t LOST_TIME
Definition pi_camera_line_following.cpp:86
const std::string SQUARE_PATH_ENDPOINT
Definition pi_camera_line_following.cpp:70
const std::string DEFAULT_SERVER
Definition pi_camera_line_following.cpp:69
const real_t SQUARE_PATH_SPEED
Definition pi_camera_line_following.cpp:92
real_t nearest_side_heading(const Path &path, const Point &p)
Definition pi_camera_line_following.cpp:347
const real_t PRINT_PERIOD
Definition pi_camera_line_following.cpp:79
const real_t STOP_GAIN
Definition pi_camera_line_following.cpp:94
std::optional< Path > find_square(const FloorImage &floor)
Definition pi_camera_line_following.cpp:224
const std::string ROBOT_FILE
Definition pi_camera_line_following.cpp:72
cv::Mat dark_pixels(const cv::Mat &gray)
Definition pi_camera_line_following.cpp:114
const real_t SEARCH_TURN_RATE
Definition pi_camera_line_following.cpp:85
const real_t TIME_LIMIT
Definition pi_camera_line_following.cpp:78
Start start_on_square(const Path &square)
Definition pi_camera_line_following.cpp:370
std::optional< std::pair< Segment, real_t > > wait_for_next_side(const MJPEG_HTTPCameraBackend &stream, real_t floor_width, real_t timeout)
Definition pi_camera_line_following.cpp:846
const real_t CRUISE_SPEED
Definition pi_camera_line_following.cpp:82
const real_t DEFAULT_FLOOR_WIDTH
Definition pi_camera_line_following.cpp:77
const real_t PI
Definition pi_camera_line_following.cpp:75
const std::string WINDOW_TITLE
Definition pi_camera_line_following.cpp:73
Start start_on_side(const Segment &side)
Definition pi_camera_line_following.cpp:396
const real_t DARK_RATIO
Definition pi_camera_line_following.cpp:95
std::array< real_t, 2 > Point
Definition pi_camera_line_following.cpp:67
std::optional< std::pair< Segment, real_t > > find_segment(const FloorImage &floor)
Definition pi_camera_line_following.cpp:304
const real_t STEP_SIZE
Definition pi_camera_line_following.cpp:76
const real_t MAX_TURN_RATE
Definition pi_camera_line_following.cpp:84
int run(const Options &options)
Definition pi_camera_line_following.cpp:876
const real_t CORNER_TURN_RATE
Definition pi_camera_line_following.cpp:93
cv::Mat to_gray(const cv::Mat &image)
Definition pi_camera_line_following.cpp:101
list values
Definition plot_losses.py:13
real_t largest(const std::vector< real_t > &v)
Definition point_to_point.cpp:46
A frame delivered by a camera backend.
Definition camera_backend_base.h:25
Definition pi_camera_line_following.cpp:406
real_t omega
Definition pi_camera_line_following.cpp:408
real_t v
Definition pi_camera_line_following.cpp:407
Definition pi_camera_line_following.cpp:124
real_t left
Definition pi_camera_line_following.cpp:127
real_t coverage
Definition pi_camera_line_following.cpp:128
bool found
Definition pi_camera_line_following.cpp:125
real_t end
Definition pi_camera_line_following.cpp:131
real_t forward
Definition pi_camera_line_following.cpp:126
bool ends
Definition pi_camera_line_following.cpp:130
cv::Point2d pixel
Definition pi_camera_line_following.cpp:129
Settings of the backend.
Definition mjpeg_http_camera_backend.h:43
std::string url
The URL of the stream, e.g. http://raspberrypi.local:8000/stream.
Definition mjpeg_http_camera_backend.h:47
Definition pi_camera_line_following.cpp:783
std::string url() const
Definition pi_camera_line_following.cpp:790
bool pi_camera
Definition pi_camera_line_following.cpp:786
std::string server
Definition pi_camera_line_following.cpp:784
real_t floor_width
Definition pi_camera_line_following.cpp:785
std::string record
Definition pi_camera_line_following.cpp:788
bool render
Definition pi_camera_line_following.cpp:787
Definition pi_camera_line_following.cpp:190
void add(const Segment &segment)
Definition pi_camera_line_following.cpp:206
real_t distance(const Point &p) const
Definition pi_camera_line_following.cpp:195
Point centre
Definition pi_camera_line_following.cpp:192
real_t line_width
Definition pi_camera_line_following.cpp:193
std::vector< Segment > segments
Definition pi_camera_line_following.cpp:191
Definition pi_camera_line_following.cpp:168
Point a
Definition pi_camera_line_following.cpp:169
Point middle() const
Definition pi_camera_line_following.cpp:172
Point b
Definition pi_camera_line_following.cpp:170
real_t distance(const Point &p) const
Definition pi_camera_line_following.cpp:175
real_t length() const
Definition pi_camera_line_following.cpp:173
Definition pi_camera_line_following.cpp:362
real_t y
Definition pi_camera_line_following.cpp:364
real_t yaw
Definition pi_camera_line_following.cpp:365
real_t x
Definition pi_camera_line_following.cpp:363
Wall clock helpers for running a simulation in real time.

The camera server:

"""Stream camera frames as MJPEG over HTTP with FastAPI.
The endpoints are the same as those of the Odysseus robot's server, so
the pi_camera_line_following example works with either:
GET /odysseus/camera the camera, as an MJPEG stream
GET /odysseus/camera/square-path generated frames of a square path, one
side at a time, as an MJPEG stream
GET /odysseus/camera/frame the latest camera frame as one JPEG
GET /odysseus/camera/info the source, frame size and frame rate
On a Raspberry Pi 5 with a camera module the camera frames come from Picamera2.
Point the camera down at a sheet of paper with a square drawn on it in thick
dark lines. On any other computer, --synthetic draws such a square instead.
The square path needs no camera. Every --period seconds its frame shows the
next side of a square, counterclockwise as seen from above: bottom, right, top,
left. The square is centred in the frame.
Usage
python camera_server.py # Pi camera, port 8000
python camera_server.py --synthetic # generated camera frames
python camera_server.py --help
"""
import argparse
import asyncio
import math
import threading
import time
import cv2
import numpy as np
import uvicorn
from fastapi import FastAPI, Response
from fastapi.responses import StreamingResponse
BOUNDARY = "frame"
class PiCameraSource:
"""Frames from the Pi camera through Picamera2."""
name = "picamera2"
def __init__(self, width, height):
# Only on the Pi: sudo apt install python3-picamera2
from picamera2 import Picamera2
self._camera = Picamera2()
# RGB888 gives the pixels in B, G, R order, which is what OpenCV uses
config = self._camera.create_video_configuration(
main={"size": (width, height), "format": "RGB888"}
)
self._camera.configure(config)
self._camera.start()
def read(self):
return self._camera.capture_array()
def close(self):
self._camera.stop()
class SyntheticSource:
"""A square of thick dark lines on paper, as a camera above it would see it.
The paper is slightly rotated and moves a little over time, and the frames
have uneven lighting and noise, so the simulator cannot rely on a perfect
picture.
"""
name = "synthetic"
def __init__(self, width, height, side=0.6, line_width=0.035, seed=1):
self._width = width
self._height = height
self._side = side # of the square, as a fraction of the frame height
self._line_width = line_width # as a fraction of the frame height
self._rng = np.random.default_rng(seed)
self._start = time.monotonic()
# Lighting: brighter in one corner, like a desk lamp
y, x = np.mgrid[0:height, 0:width].astype(np.float32)
light = 225.0 - 35.0 * (x / width + y / height) / 2.0
self._paper = np.repeat(light[:, :, None], 3, axis=2)
def read(self):
t = time.monotonic() - self._start
h = self._height
angle = math.radians(4.0 + 1.5 * math.sin(0.3 * t))
centre = np.array([self._width / 2 + 0.01 * h * math.sin(0.2 * t),
h / 2 + 0.01 * h * math.cos(0.25 * t)])
half = self._side * h / 2.0
corners = np.array([[-half, -half], [half, -half], [half, half], [-half, half]])
rotation = np.array([[math.cos(angle), -math.sin(angle)],
[math.sin(angle), math.cos(angle)]])
corners = (corners @ rotation.T + centre).astype(np.int32)
frame = self._paper.copy()
thickness = max(2, int(round(self._line_width * h)))
cv2.polylines(frame, [corners], isClosed=True, color=(40, 40, 40),
thickness=thickness, lineType=cv2.LINE_AA)
frame += self._rng.normal(0.0, 6.0, frame.shape).astype(np.float32)
time.sleep(1.0 / 60.0) # a camera does not deliver frames instantly
return np.clip(frame, 0, 255).astype(np.uint8)
def close(self):
pass
class SquarePath:
"""One side of a square at a time, the next one every period seconds."""
def __init__(self, width, height, period, side=0.5, line_width=0.035):
self.period = period
self._start = time.monotonic()
half = side * height / 2.0
cx, cy = width / 2.0, height / 2.0
# Counterclockwise as seen from above; image rows grow downwards
corners = [(cx - half, cy + half), (cx + half, cy + half),
(cx + half, cy - half), (cx - half, cy - half)]
y, x = np.mgrid[0:height, 0:width].astype(np.float32)
paper = 225.0 - 30.0 * (x / width + y / height) / 2.0
thickness = max(2, int(round(line_width * height)))
self._frames = []
for i in range(4):
frame = np.repeat(paper[:, :, None], 3, axis=2).astype(np.uint8)
start, end = corners[i], corners[(i + 1) % 4]
cv2.line(frame, (int(round(start[0])), int(round(start[1]))),
(int(round(end[0])), int(round(end[1]))), color=(40, 40, 40),
thickness=thickness, lineType=cv2.LINE_AA)
self._frames.append(cv2.imencode(".jpg", frame)[1].tobytes())
def latest(self):
"""The JPEG of the current side, and a number that changes with it"""
step = int((time.monotonic() - self._start) // self.period)
return self._frames[step % 4], step
class FrameGrabber:
"""Reads frames on a thread of its own and keeps the latest one as JPEG."""
def __init__(self, source, quality):
self._source = source
self._quality = quality
self._lock = threading.Lock()
self._jpeg = None
self._count = 0
self._running = True
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
def _run(self):
while self._running:
frame = self._source.read()
ok, jpeg = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, self._quality])
if ok:
with self._lock:
self._jpeg = jpeg.tobytes()
self._count += 1
def latest(self):
with self._lock:
return self._jpeg, self._count
def stop(self):
self._running = False
self._thread.join(timeout=1.0)
self._source.close()
def mjpeg_part(jpeg):
return (f"--{BOUNDARY}\r\nContent-Type: image/jpeg\r\n"
f"Content-Length: {len(jpeg)}\r\n\r\n").encode() + jpeg + b"\r\n"
def build_app(grabber, square_path, source_name, width, height, fps):
app = FastAPI(title="bitsim pi_camera_line_following camera")
media_type = f"multipart/x-mixed-replace; boundary={BOUNDARY}"
@app.get("/odysseus/camera/info")
def info():
_, count = grabber.latest()
return {"source": source_name, "width": width, "height": height,
"fps": fps, "frames": count, "square_path_period": square_path.period}
@app.get("/odysseus/camera/frame")
def frame():
jpeg, _ = grabber.latest()
if jpeg is None:
return Response(status_code=503)
return Response(content=jpeg, media_type="image/jpeg")
async def camera_stream():
last = 0
while True:
jpeg, count = grabber.latest()
if jpeg is not None and count != last:
last = count
yield mjpeg_part(jpeg)
await asyncio.sleep(1.0 / fps)
async def square_path_stream():
# The frame does not change for a whole side, but send it at the frame
# rate anyway, as a camera would
while True:
jpeg, _ = square_path.latest()
yield mjpeg_part(jpeg)
await asyncio.sleep(1.0 / fps)
@app.get("/odysseus/camera")
def camera():
return StreamingResponse(camera_stream(), media_type=media_type)
@app.get("/odysseus/camera/square-path")
def square_path_endpoint():
return StreamingResponse(square_path_stream(), media_type=media_type)
return app
def main():
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--synthetic", action="store_true",
help="generate frames instead of using the Pi camera")
parser.add_argument("--host", default="0.0.0.0")
parser.add_argument("--port", type=int, default=8000)
parser.add_argument("--width", type=int, default=640)
parser.add_argument("--height", type=int, default=480)
parser.add_argument("--fps", type=float, default=20.0, help="frames per second to stream")
parser.add_argument("--quality", type=int, default=80, help="JPEG quality, 1 to 100")
parser.add_argument("--period", type=float, default=5.0,
help="seconds between the sides of the square path")
args = parser.parse_args()
if args.synthetic:
source = SyntheticSource(args.width, args.height)
else:
source = PiCameraSource(args.width, args.height)
grabber = FrameGrabber(source, args.quality)
square_path = SquarePath(args.width, args.height, args.period)
app = build_app(grabber, square_path, source.name, args.width, args.height, args.fps)
try:
uvicorn.run(app, host=args.host, port=args.port, log_level="warning")
finally:
grabber.stop()
if __name__ == "__main__":
main()