1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
| #include <iostream> #include <vector> #include <string> #include <cmath> #include <algorithm> #include <opencv2/opencv.hpp>
const int INPUT_WIDTH = 224; const int INPUT_HEIGHT = 224; const int INPUT_CHANNELS = 3;
const float MEAN[] = {0.485f, 0.456f, 0.406f}; const float STD[] = {0.229f, 0.224f, 0.225f};
std::vector<float> preprocess(const cv::Mat& original_img) { cv::Mat img; cv::resize(original_img, img, cv::Size(INPUT_WIDTH, INPUT_HEIGHT));
cv::cvtColor(img, img, cv::COLOR_BGR2RGB);
img.convertTo(img, CV_32F, 1.0 / 255.0);
std::vector<float> input_tensor; input_tensor.resize(INPUT_CHANNELS * INPUT_HEIGHT * INPUT_WIDTH);
float* tensor_data = input_tensor.data();
for (int c = 0; c < INPUT_CHANNELS; ++c) { for (int h = 0; h < INPUT_HEIGHT; ++h) { for (int w = 0; w < INPUT_WIDTH; ++w) { float pixel_value = img.ptr<cv::Vec3f>(h)[w][c];
pixel_value = (pixel_value - MEAN[c]) / STD[c];
int index = c * (INPUT_HEIGHT * INPUT_WIDTH) + h * INPUT_WIDTH + w; tensor_data[index] = pixel_value; } } }
return input_tensor; }
class OnnxEngine { private: Ort::Env env; Ort::Session session; Ort::AllocatorWithDefaultOptions allocator; std::vector<const char*> input_node_names; std::vector<const char*> output_node_names; std::vector<std::string> input_node_names_alloc; std::vector<std::string> output_node_names_alloc;
public: OnnxEngine(const std::string& model_path) : env(ORT_LOGGING_LEVEL_WARNING, "TestOnnxEnv"), session(nullptr) { Ort::SessionOptions session_options; session_options.SetIntraOpNumThreads(1); session = Ort::Session(env, model_path.c_str(), session_options);
size_t num_input_nodes = session.GetInputCount(); for(size_t i = 0; i < num_input_nodes; i++) { auto input_name = session.GetInputNameAllocated(i, allocator); input_node_names_alloc.push_back(input_name.get()); input_node_names.push_back(input_node_names_alloc.back().c_str()); }
size_t num_output_nodes = session.GetOutputCount(); for(size_t i = 0; i < num_output_nodes; i++) { auto output_name = session.GetOutputNameAllocated(i, allocator); output_node_names_alloc.push_back(output_name.get()); output_node_names.push_back(output_node_names_alloc.back().c_str()); } std::cout << "Model loaded. Input Name: " << input_node_names[0] << std::endl; }
std::vector<float> run_inference(std::vector<float>& input_data) { std::vector<int64_t> input_shape = {1, 3, 224, 224}; Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu( OrtArenaAllocator, OrtMemTypeDefault);
Ort::Value input_tensor = Ort::Value::CreateTensor<float>( memory_info, input_data.data(), input_data.size(), input_shape.data(), input_shape.size() );
auto output_tensors = session.Run( Ort::RunOptions{nullptr}, input_node_names.data(), &input_tensor, 1, output_node_names.data(), 1 );
float* floatarr = output_tensors[0].GetTensorMutableData<float>(); size_t output_size = output_tensors[0].GetTensorTypeAndShapeInfo().GetElementCount(); return std::vector<float>(floatarr, floatarr + output_size); } };
std::vector<float> softmax(const std::vector<float>& logits) { std::vector<float> probabilities(logits.size()); float sum = 0.0f; float max_val = *std::max_element(logits.begin(), logits.end());
for (size_t i = 0; i < logits.size(); ++i) { probabilities[i] = std::exp(logits[i] - max_val); sum += probabilities[i]; }
for (size_t i = 0; i < probabilities.size(); ++i) { probabilities[i] /= sum; }
return probabilities; }
int main() { std::string image_path = "cat.jpg"; std::string model_path = "resnet50.onnx";
cv::Mat img = cv::imread(image_path); if (img.empty()) { std::cerr << "Error reading image." << std::endl; return -1; }
std::cout << "Loading model..." << std::endl; try { OnnxEngine engine(model_path);
std::vector<float> input_tensor = preprocess(img);
std::vector<float> output_logits = engine.run_inference(input_tensor);
std::vector<float> probs = softmax(output_logits);
auto max_it = std::max_element(probs.begin(), probs.end()); int class_id = std::distance(probs.begin(), max_it); float confidence = *max_it;
std::cout << "--------------------------------" << std::endl; std::cout << "Class ID: " << class_id << ", Probability: " << confidence * 100 << "%" << std::endl; std::cout << "--------------------------------" << std::endl;
} catch (const Ort::Exception& e) { std::cerr << "ONNX Runtime Error: " << e.what() << std::endl; }
return 0; }
|