#include <vector>
#include <cmath>
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace cv::dnn;
using namespace std;
int main() {
Mat img = imread("你要分割的图片.jpg");
String modelFile = "你的分割模型.onnx";
if (img.empty()) {
cout << "未找到图片!" << endl;
return -1;
}
try {
//原始图片大小
int org_width = img.cols;
int org_height = img.rows;
//计算缩放比例
double scale = 1.0;
if (org_width >= org_height) {
scale = (double)512 / org_width;
}
else {
scale = (double)512 / org_height;
}
//缩放图片,并保持长宽比
Mat resized_img;
resize(img, resized_img, Size(), scale, scale);
//计算灰度填充的大小
int pad_x = (512 - resized_img.cols) / 2;
int pad_y = (512 - resized_img.rows) / 2;
//加上灰色填充
Mat padded_img = Mat::zeros(512, 512, CV_8UC1);
copyMakeBorder(resized_img, padded_img, pad_y, pad_y, pad_x, pad_x, BORDER_CONSTANT, Scalar(128));
//图片通道转换和resize
padded_img.convertTo(padded_img, CV_32FC3, 1.f / 255.f);
cv::cvtColor(padded_img, padded_img, cv::COLOR_BGR2RGB);
cv::resize(padded_img, padded_img, cv::Size(512, 512), 0, 0, cv::INTER_LINEAR);
Mat inputBolb = blobFromImage(padded_img);
dnn::Net net = cv::dnn::readNetFromONNX(modelFile);
net.setInput(inputBolb);
Mat output = net.forward();
int N = inputBolb.size[0];
int C = inputBolb.size[1];
int H = inputBolb.size[2];
int W = inputBolb.size[3];
Mat predMat = Mat::zeros(512, 512, CV_32F);
for (int h = 0; h < H; h++) {
for (int w = 0; w < W; w++) {
float bg = output.ptr<float>(0, 0, h)[w];
float c1 = output.ptr<float>(0, 1, h)[w];
float c2 = output.ptr<float>(0, 2, h)[w];
float c3 = output.ptr<float>(0, 3, h)[w];
if (bg >= c1 && bg >= c2 && bg >= c3) {//背景
predMat.at<float>(h, w) = 255;
}
else if (c1 >= c2 && c1 >= c3) {//类别1
predMat.at<float>(h, w) = 200;
}
else if (c2 >= c1 && && c2 >= c3) {//类别2
predMat.at<float>(h, w) = 150;
}
else {//类别3
predMat.at<float>(h, w) = 0;
}
}
}
//去除灰色填充并还原原始大小
Rect roi(pad_x, pad_y, org_width * scale, org_height * scale);
Mat roi_img = predMat(roi);
resize(roi_img, roi_img, Size(org_width, org_height));
imshow("seg.png", roi_img);
WaitKey(0);
}
catch (char* str)
{
cout << str << endl;
}
catch (int i)
{
cout << i << endl;
}
return 0;
}
OpenCV DNN模块进行深度学习
最新推荐文章于 2024-08-15 19:57:00 发布