Files
vslam_cpp/libs/vslam_sim/src/occupancy_map_io.cc
trung09122002 48bd5377dc upload
2026-09-18 18:14:42 +07:00

249 lines
8.0 KiB
C++

#include "vslam/occupancy_map_io.h"
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <vector>
#include "vslam/log.h"
namespace vslam {
namespace {
std::string DirName(const std::string& path) {
const size_t slash = path.find_last_of('/');
return slash == std::string::npos ? std::string(".") : path.substr(0, slash);
}
// Doc PGM P5 (nhi phan 8 bit). Bo qua comment bat dau bang '#'.
bool ReadPgm(const std::string& path, uint32_t* w, uint32_t* h,
std::vector<uint8_t>* pixels, std::string* err) {
std::ifstream f(path, std::ios::binary);
if (!f) {
*err = "khong mo duoc " + path;
return false;
}
auto next_token = [&f]() -> std::string {
std::string tok;
while (f) {
const int c = f.get();
if (c == EOF) break;
if (c == '#') {
while (f && f.get() != '\n') {
}
continue;
}
if (std::isspace(c)) {
if (!tok.empty()) break;
continue;
}
tok.push_back(static_cast<char>(c));
}
return tok;
};
if (next_token() != "P5") {
*err = path + ": chi ho tro PGM P5 (nhi phan)";
return false;
}
*w = static_cast<uint32_t>(std::stoul(next_token()));
*h = static_cast<uint32_t>(std::stoul(next_token()));
const unsigned long maxval = std::stoul(next_token());
if (maxval > 255) {
*err = path + ": chi ho tro PGM 8 bit";
return false;
}
pixels->resize(static_cast<size_t>(*w) * (*h));
f.read(reinterpret_cast<char*>(pixels->data()),
static_cast<std::streamsize>(pixels->size()));
if (static_cast<size_t>(f.gcount()) != pixels->size()) {
*err = path + ": file anh cut";
return false;
}
return true;
}
} // namespace
StatusResponse LoadOccupancyMap(const std::string& yaml_path, MapLoadResult* out) {
// Kiem TON TAI truoc khi giao cho yaml-cpp.
//
// `YAML::LoadFile` tren mot file khong co nem `BadFile`, va `what()` cua no
// dung la chuoi "bad file" -- khong noi file nao, khong phan biet thieu voi
// hong, khong goi y gi. Nguoi dung go sai duong dan chi nhan duoc
// "hospital.yaml: bad file" roi dung do.
{
std::ifstream probe(yaml_path);
if (!probe) {
return StatusResponse::Error(
StatusCode::kNotFound,
"khong mo duoc ban do: " + yaml_path +
" (khong ton tai hoac khong co quyen doc). Xuat mot ban do tu DB "
"RTAB-Map bang: vslam_slam_bench --db X.db --localize "
"--export-only --export-map out.pgm");
}
}
YAML::Node node;
try {
node = YAML::LoadFile(yaml_path);
} catch (const YAML::Exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
yaml_path + ": YAML hong: " + e.what());
}
if (!node["image"] || !node["resolution"]) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
yaml_path + ": thieu 'image' hoac 'resolution'");
}
std::string image = node["image"].as<std::string>();
if (!image.empty() && image[0] != '/') image = DirName(yaml_path) + "/" + image;
out->image_path = image;
const double resolution = node["resolution"].as<double>();
double ox = 0.0, oy = 0.0;
if (node["origin"] && node["origin"].size() >= 2) {
ox = node["origin"][0].as<double>();
oy = node["origin"][1].as<double>();
}
const bool negate = node["negate"] ? node["negate"].as<int>() != 0 : false;
out->occupied_thresh =
node["occupied_thresh"] ? node["occupied_thresh"].as<double>() : 0.65;
out->free_thresh = node["free_thresh"] ? node["free_thresh"].as<double>() : 0.196;
uint32_t w = 0, h = 0;
std::vector<uint8_t> pixels;
std::string err;
if (!ReadPgm(image, &w, &h, &pixels, &err)) {
return StatusResponse::Error(StatusCode::kNotFound, err);
}
out->grid.width = w;
out->grid.height = h;
out->grid.resolution = static_cast<float>(resolution);
out->grid.origin.position.x = ox;
out->grid.origin.position.y = oy;
out->grid.data.resize(static_cast<size_t>(w) * h);
for (uint32_t y = 0; y < h; ++y) {
for (uint32_t x = 0; x < w; ++x) {
// PGM hang 0 o TREN CUNG; occupancy grid hang 0 o DUOI CUNG (goc o
// origin). Quen lat truc y la loi kinh dien khi doc map, va hau qua la
// ban do bi lat nguoc ma van "trong nhu that".
const uint8_t px = pixels[static_cast<size_t>(h - 1 - y) * w + x];
double occ = (255.0 - static_cast<double>(px)) / 255.0;
if (negate) occ = 1.0 - occ;
int8_t v;
if (occ > out->occupied_thresh) {
v = 100;
} else if (occ < out->free_thresh) {
v = 0;
} else {
v = -1; // chua biet
}
out->grid.data[static_cast<size_t>(y) * w + x] = v;
}
}
VSLAM_INFO("map: nap " << image << " -- " << w << "x" << h << " @ "
<< resolution << " m/o, goc (" << ox << ", " << oy << ")");
return StatusResponse::Ok();
}
StatusResponse SaveOccupancyMap(const OccupancyGrid& grid,
const std::string& yaml_path) {
std::string base = yaml_path;
const size_t dot = base.find_last_of('.');
if (dot != std::string::npos) base = base.substr(0, dot);
const std::string pgm_path = base + ".pgm";
std::ofstream img(pgm_path, std::ios::binary);
if (!img) {
return StatusResponse::Error(StatusCode::kUnavailable,
"khong ghi duoc " + pgm_path);
}
img << "P5\n# sinh boi vslam\n" << grid.width << " " << grid.height << "\n255\n";
for (uint32_t y = 0; y < grid.height; ++y) {
for (uint32_t x = 0; x < grid.width; ++x) {
const int8_t v = grid.data[static_cast<size_t>(grid.height - 1 - y) * grid.width + x];
const uint8_t px = v < 0 ? 205 : (v >= 50 ? 0 : 254);
img.put(static_cast<char>(px));
}
}
img.close();
std::ofstream y(yaml_path);
if (!y) {
return StatusResponse::Error(StatusCode::kUnavailable,
"khong ghi duoc " + yaml_path);
}
const size_t slash = pgm_path.find_last_of('/');
y << "image: " << (slash == std::string::npos ? pgm_path : pgm_path.substr(slash + 1))
<< "\nresolution: " << grid.resolution << "\norigin: [" << grid.origin.position.x
<< ", " << grid.origin.position.y << ", 0.0]\nnegate: 0\n"
<< "occupied_thresh: 0.65\nfree_thresh: 0.196\n";
VSLAM_INFO("map: da ghi " << yaml_path << " va " << pgm_path);
return StatusResponse::Ok();
}
OccupancyGrid MakeSyntheticWorld(uint32_t w, uint32_t h, float res) {
OccupancyGrid m;
m.width = w;
m.height = h;
m.resolution = res;
m.origin.position.x = -static_cast<double>(w) * res / 2.0;
m.origin.position.y = -static_cast<double>(h) * res / 2.0;
m.data.assign(static_cast<size_t>(w) * h, -1);
auto put = [&](uint32_t x, uint32_t y, int8_t v) {
if (x < w && y < h) m.data[static_cast<size_t>(y) * w + x] = v;
};
const uint32_t cy = h / 2;
const uint32_t half = std::max<uint32_t>(6, h / 24);
for (uint32_t x = w / 10; x < w - w / 10; ++x) {
for (uint32_t y = cy - half; y <= cy + half; ++y) put(x, y, 0);
put(x, cy - half - 1, 100);
put(x, cy + half + 1, 100);
}
// Bit hai dau hanh lang, neu khong thi raycast chay ra vo tan.
for (uint32_t y = cy - half - 1; y <= cy + half + 1; ++y) {
put(w / 10, y, 100);
put(w - w / 10 - 1, y, 100);
}
const uint32_t room = half * 3;
for (uint32_t rx = w / 6; rx + room < w - w / 10; rx += room + room / 2) {
for (int side = 0; side < 2; ++side) {
const uint32_t y0 = side == 0 ? cy + half + 2 : cy - half - 2 - room;
for (uint32_t x = rx; x < rx + room; ++x) {
for (uint32_t y = y0; y < y0 + room; ++y) put(x, y, 0);
}
for (uint32_t x = rx - 1; x <= rx + room; ++x) {
put(x, y0 - 1, 100);
put(x, y0 + room, 100);
}
for (uint32_t y = y0 - 1; y <= y0 + room; ++y) {
put(rx - 1, y, 100);
put(rx + room, y, 100);
}
const uint32_t door = rx + room / 2;
for (uint32_t x = door - 2; x <= door + 2; ++x) {
put(x, side == 0 ? y0 - 1 : y0 + room, 0);
}
}
}
return m;
}
} // namespace vslam