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
| #include <iostream> #include <string> #include <vector> #include<opencv2/opencv.hpp> #include <opencv2/dnn.hpp> using namespace std; void readImagesInFolder(const std::string& folderPath, std::vector<cv::Mat>& images) { cv::String path(folderPath + "/*.jpg"); std::vector<cv::String> fileNames; cv::glob(path, fileNames, true); for (const auto& fileName : fileNames) { cv::Mat bgrImage = cv::imread(fileName, cv::IMREAD_COLOR); if (!bgrImage.empty()) { cv::Mat rgbImage; cv::cvtColor(bgrImage, rgbImage, cv::COLOR_BGR2RGB); images.push_back(rgbImage); } } }
cv::Mat transformation(const cv::Mat& image, const cv::Size & targetSize, const cv::Scalar& mean, const cv::Scalar& std) {
cv::Mat resizedImage; cv::resize(image, resizedImage, targetSize, 0, 0, cv::INTER_AREA); cv::Mat normalized; resizedImage.convertTo(normalized, CV_32F); cv::subtract(normalized / 255.0, mean, normalized); cv::divide(normalized, std, normalized); return normalized; } cv::dnn::Net loadModel(const string& onnx_path) { cv::dnn::Net net = cv::dnn::readNetFromONNX(onnx_path); return net; } int main() { string folderPath = "D:/C++_demo/opencv_onnx_gpu/CAMO/c"; std::vector<cv::Mat> rgbImages; readImagesInFolder(folderPath, rgbImages);
string onnx_path = "D:/C++_demo/opencv_onnx_gpu/PFNet.onnx"; cv::dnn::Net net = loadModel(onnx_path); net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA); net.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA); cv::Mat output_prob; std::vector<cv::Mat> output_probs; std::vector<cv::String> output_layer_names = net.getUnconnectedOutLayersNames();
cv::Size targetSize(416, 416); cv::Scalar mean(0.485, 0.456, 0.406); cv::Scalar std(0.229, 0.224, 0.225);
auto start = chrono::high_resolution_clock::now(); for (const auto& rgbImage : rgbImages) { cv::Size originalSize(rgbImage.cols, rgbImage.rows); cv::Mat normalized = transformation(rgbImage, targetSize, mean, std); std::cout << normalized.size() << std::endl; cv::Mat blob = cv::dnn::blobFromImage(normalized); net.setInput(blob); net.forward(output_probs, output_layer_names); cv::Mat prediction = output_probs[3]; cv::Mat mask; cv::resize(prediction.reshape(1, 416) * 255.0, mask, originalSize, 0, 0, cv::INTER_AREA); } auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed = end - start; double elapsedTime = elapsed.count(); std::cout << "Elapsed time: " << elapsedTime << " seconds" << std::endl; return 0; }
|