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, 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}
\]
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 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.
Either way the robot goes around counterclockwise.
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.
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.
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
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.
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:
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.
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.
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.
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:
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.
The robot never lost the line. It cut the corners, as it turns before its axle reaches them.
#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
WINDOW_TITLE =
"A line following robot with a Raspberry Pi camera";
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;
}
{
std::vector<uchar>
values(gray.begin<uchar>(), gray.end<uchar>());
auto paper =
values.begin() +
static_cast<long>(0.9 * (
values.size() - 1));
}
{
};
{
const cv::Moments m = cv::moments(dark, true);
reading.coverage = m.m00 /
static_cast<real_t>(dark.total());
{
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];
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;
}
{
Point middle()
const {
return {0.5 * (
a[0] +
b[0]), 0.5 * (
a[1] +
b[1])}; }
{
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);
}
};
{
{
real_t best = std::numeric_limits<real_t>::max();
{
best = std::min(best, segment.distance(p));
}
return best;
}
void add(
const Segment &segment)
{
{
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;
}
}
}
};
{
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;
}
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);
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;
}
{
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_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;
}
(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());
}
{
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]);
}
{
};
{
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])};
}
{
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])};
}
{
};
{
public:
{
};
: half_view_width_(half_view_width), cruise_speed_(cruise_speed), when_lost_(when_lost),
{
}
{
if (!line.found)
{
lost_for_ += dt;
{
return {};
}
}
lost_for_ = 0.0;
last_left_ = line.left;
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);
}
bool has_given_up()
const {
return lost_for_ > give_up_after_; }
private:
};
{
public:
{
};
: follower_(follower), near_edge_(near_edge), half_line_width_(half_line_width)
{
}
{
const Point ahead{std::cos(heading), std::sin(heading)};
switch (state_)
{
if (line.found)
{
followed_heading_ = side_heading;
}
if (line.found && line.ends)
{
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_))
{
break;
}
return follower_.command(line, dt);
{
((*corner_)[0] - position[0]) * ahead[0] + ((*corner_)[1] - position[1]) * ahead[1];
if (remaining > 0.01)
{
}
turn_to_ = followed_heading_ + 0.5 *
PI;
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);
}
break;
break;
}
{
if (line.found)
{
corner_.reset();
return follower_.command(line, dt);
}
waited_ += dt;
return {};
}
return command(line, position, heading, side_heading, dt);
}
private:
LineFollower follower_;
std::optional<Point> corner_;
real_t followed_heading_{0.0};
};
{
public:
explicit World(
const Start &start)
{
system_.SetGravitationalAcceleration(
system_.SetCollisionSystemType(chrono::ChCollisionSystem::Type::BULLET);
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);
if (!robot_.get_camera())
{
throw std::runtime_error(
"The robot file " +
ROBOT_FILE +
" has no front-camera");
}
robot_.add_to_sys(system_);
}
void step(
const Command &command)
{
}
real_t time()
const {
return system_.GetChTime(); }
Point position()
const {
return {robot_.axle_center().x(), robot_.axle_center().y()}; }
const CHRONO_DiffDriveRobot &
robot()
const {
return robot_; }
private:
chrono::ChSystemNSC system_;
CHRONO_DiffDriveRobot robot_;
};
{
public:
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_)
{
}
}
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);
};
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);
}
const auto &robot = world.robot();
const auto &data = robot.get_data();
const Point c = world.position();
const real_t yaw = world.heading();
{
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);
}
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);
}
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);
if (!record_.empty() && world.time() + 1e-9 >= next_record_)
{
next_record_ += 1.0 / frame_rate_;
if (!writer_.isOpened())
{
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;
}
const int key = cv::waitKey(1);
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_;
cv::VideoWriter writer_;
bool was_visible_{false};
};
{
{
}
};
{
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"
<< 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;
}
{
std::optional<Point> first;
const auto start = std::chrono::steady_clock::now();
{
const auto frame = stream.latest_frame();
if (frame &&
frame->index != last_index)
{
last_index =
frame->index;
{
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;
}
{
{
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();
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;
}
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";
if (options.pi_camera)
{
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;
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();
path.line_width = side->second;
path.add(first);
std::cout << "Side: " << first.length() << " m long, line " << path.line_width
<< " m wide\n";
}
const auto &camera = *world.robot().get_camera();
const real_t half_view_width = 0.5 * camera.config().view_width;
const real_t near_edge = camera.config().offset - 0.5 * camera.config().view_length;
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;
cv::Mat view;
std::vector<Point> trail;
real_t last_angle = std::atan2(
start.y - path.centre[1],
start.x - path.centre[0]);
bool completed = false;
bool stopped = false;
const auto wall_start = std::chrono::steady_clock::now();
{
if (world.time() >= next_image)
{
next_image += camera_period;
if (
const auto latest = stream.latest_frame(); latest && latest->index !=
frame.index)
{
if (!options.pi_camera)
{
{
}
}
}
frame_age_sum += frame_age;
view = world.robot().camera_view(floor);
options.pi_camera
? follower.command(line, camera_period)
: driver.command(line, world.position(), world.heading(),
++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;
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)
{
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(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;
}
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));
}
}
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;
}
}
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 ¢re)
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.
"""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):
from picamera2 import Picamera2
self._camera = Picamera2()
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
self._line_width = line_width
self._rng = np.random.default_rng(seed)
self._start = time.monotonic()
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)
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
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():
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
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__":