基于最新C++深度学习框架和计算机视觉库,识别包括猫、狗、狮子等常见动物类别

基于最新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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员Thomas

谢谢您的打赏,我将会更好创作。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值