基于最新C++深度学习框架和计算机视觉库,以下提供可直接编译运行的动物图像识别系统完整源码。该系统结合LibTorch(PyTorch C++接口)和OpenCV实现,支持识别包括猫、狗、狮子等常见动物类别。
//cpp
// animal_recognition.cpp
#include <torch/script.h>
#include <opencv2/opencv.hpp>
#include
const std::vectorstd::string CLASS_NAMES = {
“猫”, “狗”, “狮子”, “老虎”, “斑马”,
“长颈鹿”, “企鹅”, “猎豹”, “犀牛”, “大象”
};
// 图像预处理
torch::Tensor preprocess(cv::Mat image) {
// 转换为RGB格式
cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
// 调整尺寸并归一化
cv::resize(image, image, cv::Size(224, 224));
image.convertTo(image, CV_32FC3, 1.0f / 255.0f);
// 转换为Tensor
auto tensor = torch::from_blob(image.data, {224, 224, 3}, torch::kFloat32);
tensor = tensor.permute({2, 0, 1}); // CHW格式
tensor = tensor.unsqueeze(0); // 增加batch维度
// 标准化(与训练时参数一致)
tensor[0][0] = tensor[0][0].sub_(0.485).div_(0.229);
tensor[0][1] = tensor[0][1].sub_(0.456).div_(0.224);
tensor[0][2] = tensor[0][2].sub_(0.406).div_(0.225);
return tensor.clone();
}
int main() {
// 加载TorchScript模型
torch::jit::script::Module module;
try {
module = torch::jit::load(“animal_resnet18.pt”);
} catch (const c10::Error& e) {
std::cerr << "模型加载失败: " << e.what() << std::endl;
return -1;
}
// 加载测试图像
cv::Mat image = cv::imread("test_image.jpg");
if(image.empty()) {
std::cerr << "图像加载失败" << std::endl;
return -1;
}
// 预处理
torch::Tensor input_tensor = preprocess(image);
// 模型推理
std::vector<torch::jit::IValue> inputs;
inputs.push_back(input_tensor);
auto output = module.forward(inputs).toTensor();
// 获取预测结果
auto pred = output.argmax(1);
int index = pred.item<int>();
std::cout << "识别结果: " << CLASS_NAMES[index]
<< " (置信度: " << output.softmax(1)[0][index].item<float>() * 100
<< "%)" << std::endl;
ret