SavyaSanchi-Sharma
tensorflow_inception_graph
4249ce0
Raw
History Blame
1.99 kB
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace cv;
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", "");
Mat img = imread(image);
if (img.empty())
{
std::cerr << "could not read image: " << image << std::endl;
return 1;
}
Mat rgb;
cvtColor(img, rgb, COLOR_BGR2RGB);
resize(rgb, rgb, Size(224, 224));
rgb.convertTo(rgb, CV_32F);
int dims[] = {1, 224, 224, 3};
Mat blob(4, dims, CV_32F, rgb.data);
dnn::Net net = dnn::readNet(model);
net.setInput(blob);
Mat scores = net.forward().reshape(1, 1);
Point classId;
double conf;
minMaxLoc(scores, 0, &conf, 0, &classId);
std::string label = std::to_string(classId.x);
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 (classId.x < (int)names.size()) label = names[classId.x];
}
std::cout << "class " << classId.x << " " << label << " confidence " << conf << std::endl;
Mat out = img.clone();
putText(out, format("%s (%.2f)", label.c_str(), conf), Point(10, 30),
FONT_HERSHEY_SIMPLEX, 1.0, Scalar(0, 255, 0), 2);
imwrite(output, out);
std::cout << "wrote " << output << std::endl;
return 0;
}