采用ONNX格式的deeplabv3+网络进行语义分割的C++代码
时间: 2024-03-05 09:50:35 浏览: 119
基于onnxruntime+opencv部署yolov8的onnx模型支持检测分割旋转框C++源码+使用说明
5星 · 资源好评率100%
以下是采用ONNX格式的deeplabv3+网络进行语义分割的C++代码:
```
#include <onnxruntime_cxx_api.h>
#include <opencv2/opencv.hpp>
int main() {
// Load the ONNX model
Ort::SessionOptions session_options;
Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "test");
Ort::Session session(env, "deeplabv3plus.onnx", session_options);
// Get the input and output names and shapes
Ort::AllocatorWithDefaultOptions allocator;
std::vector<const char*> input_names = {"image"};
std::vector<const char*> output_names = {"output"};
std::vector<int64_t> input_shape = {1, 3, 512, 512};
std::vector<int64_t> output_shape;
Ort::TypeInfo output_type_info = session.GetOutputTypeInfo(0);
auto output_tensor_info = output_type_info.GetTensorTypeAndShapeInfo();
output_tensor_info.GetShape(output_shape);
// Create the input and output tensors
auto input_tensor = Ort::Value::CreateTensor<float>(allocator, input_shape.data(), input_shape.size());
auto output_tensor = Ort::Value::CreateTensor<float>(allocator, output_shape.data(), output_shape.size());
// Read the input image
cv::Mat image = cv::imread("test.png");
cv::resize(image, image, cv::Size(512, 512));
image.convertTo(image, CV_32FC3, 1.f / 255.f);
cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
// Copy the image data to the input tensor
float* input_data = input_tensor->GetTensorMutableData<float>();
memcpy(input_data, image.data, sizeof(float) * input_shape[1] * input_shape[2] * input_shape[3]);
// Run the inference
session.Run(Ort::RunOptions{nullptr}, input_names.data(), &input_tensor, 1, output_names.data(), 1, &output_tensor);
// Copy the output tensor data to an OpenCV Mat
cv::Mat output_image(output_shape[2], output_shape[3], CV_32FC1, output_tensor->GetTensorMutableData<float>());
cv::Mat output_image_normalized;
cv::normalize(output_image, output_image_normalized, 0, 255, cv::NORM_MINMAX, CV_8UC1);
// Display the output image
cv::imshow("Output", output_image_normalized);
cv::waitKey(0);
return 0;
}
```
这段代码使用了 ONNX Runtime C++ API 来加载 deeplabv3+ 模型并进行推理。输入图像的尺寸为 512x512,输出为一个概率图,每个像素点的值表示属于每个类别的概率。在这里,我们将输出图像归一化到了 0-255 的范围内,并将其展示出来。
阅读全文