| #include <opencv2/dnn.hpp> |
| #include <opencv2/imgproc.hpp> |
| #include <opencv2/imgcodecs.hpp> |
| #include <algorithm> |
| #include <array> |
| #include <fstream> |
| #include <iostream> |
| #include <string> |
| #include <vector> |
|
|
| static std::string argVal(int argc, char** argv, const std::string& key, const std::string& def) |
| { |
| for (int i = 1; i + 1 < argc; ++i) |
| if (key == argv[i]) return argv[i + 1]; |
| return def; |
| } |
|
|
| int main(int argc, char** argv) |
| { |
| std::string model = argVal(argc, argv, "--model", "tensorflow_inception_graph_2026jul.onnx"); |
| std::string image = argVal(argc, argv, "--image", "example_outputs/input_image.png"); |
| std::string output = argVal(argc, argv, "--output", "example_outputs/output_image.png"); |
| std::string labels = argVal(argc, argv, "--labels", ""); |
|
|
| cv::Mat img = cv::imread(image); |
| if (img.empty()) |
| { |
| std::cerr << "could not read image: " << image << std::endl; |
| return 1; |
| } |
|
|
| cv::Mat rgb; |
| cv::cvtColor(img, rgb, cv::COLOR_BGR2RGB); |
| cv::resize(rgb, rgb, cv::Size(224, 224)); |
| rgb.convertTo(rgb, CV_32F); |
| if (!rgb.isContinuous()) rgb = rgb.clone(); |
|
|
| int blobShape[] = {1, 224, 224, 3}; |
| cv::Mat blob(4, blobShape, CV_32F, rgb.data); |
| cv::dnn::Net net = cv::dnn::readNetFromONNX(model); |
| net.setInput(blob); |
| cv::Mat scoresMat = net.forward(); |
| float* scores = (float*)scoresMat.data; |
| int n = (int)scoresMat.total(); |
| int top = (int)(std::max_element(scores, scores + n) - scores); |
| float conf = scores[top]; |
|
|
| std::string label = std::to_string(top); |
| if (!labels.empty()) |
| { |
| std::ifstream f(labels); |
| std::vector<std::string> names; |
| std::string line; |
| while (std::getline(f, line)) names.push_back(line); |
| if (top < (int)names.size()) label = names[top]; |
| } |
| std::cout << "class " << top << " " << label << " confidence " << conf << std::endl; |
|
|
| cv::Mat out = img.clone(); |
| cv::putText(out, cv::format("%s (%.2f)", label.c_str(), conf), cv::Point(10, 30), |
| cv::FONT_HERSHEY_SIMPLEX, 1.0, cv::Scalar(0, 255, 0), 2); |
| cv::imwrite(output, out); |
| std::cout << "wrote " << output << std::endl; |
| return 0; |
| } |
|
|