Files
ModelTrainEval/deploy/cpp/main.cpp
T

84 lines
3.4 KiB
C++

// 演示与对拍工具:读一张原始像素转储,推理并打印框。
//
// 单张: ./film_predict <model.xml> <image.bin> <宽> <高> <通道> [conf] [overlap]
// 批量: ./film_predict <model.xml> --manifest <清单> [conf] [overlap]
//
// 输入是连续的 HWC uint8 缓冲(用 scripts/dump_raw.py 从图片生成)。产线里通常直接
// 拿相机帧的指针,不需要这一步。
//
// 清单每行 `路径 宽 高 通道`,模型只加载一次——逐张起进程的话加载耗时会盖过推理。
#include "film_detector.hpp"
#include <cstdio>
#include <fstream>
#include <iostream>
#include <vector>
namespace {
bool read_pixels(const std::string& path, size_t expected, std::vector<unsigned char>& out) {
std::ifstream file(path, std::ios::binary);
if (!file) { std::cerr << "打不开 " << path << "\n"; return false; }
out.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
if (out.size() != expected) {
std::cerr << path << " 的缓冲是 " << out.size() << " 字节,应为 " << expected << "\n";
return false;
}
return true;
}
void run_one(const film::Detector& detector, const film::ImageView& image, float conf,
int overlap) {
const auto boxes = (image.width == detector.input_size() &&
image.height == detector.input_size())
? detector.infer_tile(image, conf)
: detector.infer(image, conf, 0.5f, overlap);
std::printf("%zu\n", boxes.size());
for (const auto& b : boxes) {
std::printf("%d %.6f %.6f %.6f %.6f %.4f\n",
b.class_id, b.x1, b.y1, b.x2, b.y2, b.score);
}
}
} // namespace
int main(int argc, char** argv) {
if (argc < 4) {
std::cerr << "用法:\n " << argv[0] << " <model.xml> <image.bin> <宽> <高> <通道>"
<< " [conf] [overlap]\n " << argv[0]
<< " <model.xml> --manifest <清单> [conf] [overlap]\n";
return 1;
}
const std::string model_path = argv[1];
const bool batch = std::string(argv[2]) == "--manifest";
const float conf = batch ? (argc > 4 ? std::stof(argv[4]) : 0.25f)
: (argc > 6 ? std::stof(argv[6]) : 0.25f);
const int overlap = batch ? (argc > 5 ? std::stoi(argv[5]) : 32)
: (argc > 7 ? std::stoi(argv[7]) : 32);
film::Detector detector(model_path);
std::vector<unsigned char> pixels;
if (batch) {
std::ifstream manifest(argv[3]);
if (!manifest) { std::cerr << "打不开清单 " << argv[3] << "\n"; return 1; }
std::string path;
int width = 0, height = 0, channels = 0;
while (manifest >> path >> width >> height >> channels) {
if (!read_pixels(path, static_cast<size_t>(width) * height * channels, pixels)) {
return 1;
}
run_one(detector, film::ImageView{pixels.data(), width, height, channels},
conf, overlap);
}
return 0;
}
if (argc < 6) { std::cerr << "单张模式需要 宽 高 通道\n"; return 1; }
const int width = std::stoi(argv[3]), height = std::stoi(argv[4]);
const int channels = std::stoi(argv[5]);
if (!read_pixels(argv[2], static_cast<size_t>(width) * height * channels, pixels)) return 1;
run_one(detector, film::ImageView{pixels.data(), width, height, channels}, conf, overlap);
return 0;
}