YoloFeatureExtractor.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. #include "../pch/pch.h"
  2. #include "YoloFeatureExtractor.h"
  3. #include <fstream>
  4. #include <algorithm>
  5. #include <iostream>
  6. #include <functional>
  7. #include <numeric>
  8. #include "../tool/debuglog.h"
  9. YoloFeatureExtractor::YoloFeatureExtractor(const std::string & modelPath, const std::string & classesPath)
  10. : inputWidth(224), inputHeight(224)
  11. {
  12. net = cv::dnn::readNetFromONNX(modelPath);
  13. loadClassNames(classesPath);
  14. }
  15. void YoloFeatureExtractor::loadClassNames(const std::string & file)
  16. {
  17. std::ifstream ifs(file);
  18. std::string line;
  19. while (std::getline(ifs, line))
  20. {
  21. classNames.push_back(line);
  22. }
  23. }
  24. std::vector<float> YoloFeatureExtractor::globalAveragePooling(const cv::Mat & featureMap)
  25. {
  26. std::vector<float> features;
  27. // 检查特征图是否为空
  28. if (featureMap.empty())
  29. {
  30. std::cerr << "特征图为空" << std::endl;
  31. return features;
  32. }
  33. // 获取特征图维度信息
  34. int dims = featureMap.dims;
  35. if (dims < 2)
  36. {
  37. std::cerr << "特征图维度不足" << std::endl;
  38. return features;
  39. }
  40. // featureMap形状: [1, channels, height, width]
  41. int channels = featureMap.size[1];
  42. int height = featureMap.size[2];
  43. int width = featureMap.size[3];
  44. // 重塑为 [channels, height*width]
  45. cv::Mat reshaped = featureMap.reshape(1, channels);
  46. cv::Mat pooled;
  47. // 对每个通道进行平均池化
  48. cv::reduce(reshaped, pooled, 1, cv::REDUCE_AVG);
  49. // 重塑为 [1, channels] 特征向量
  50. return pooled.reshape(1, 1);
  51. }
  52. std::vector<float> YoloFeatureExtractor::extractFeatures(const std::string & imagePath)
  53. {
  54. try
  55. {
  56. auto time_1 = std::chrono::high_resolution_clock::now();
  57. cv::Mat image = cv::imread(imagePath);
  58. if (image.empty())
  59. {
  60. throw std::runtime_error("Could not load image: " + imagePath);
  61. }
  62. cv::Mat resizedImage;
  63. //cv::resize(image, resizedImage, cv::Size(inputWidth, inputHeight));
  64. cv::Mat blob;
  65. cv::dnn::blobFromImage(image, blob, 1.0 / 255.0, cv::Size(inputWidth, inputHeight), cv::Scalar(0, 0, 0), true, false);
  66. net.setInput(blob);
  67. auto time_2 = std::chrono::high_resolution_clock::now();
  68. std::vector<cv::String> layerNames = net.getLayerNames();
  69. std::vector<cv::String> outputNames;
  70. // 选择GAP层(对于yolo2026,通常是倒数第6层)的输出作为特征向量
  71. outputNames.push_back(layerNames[layerNames.size() - 6]);
  72. std::vector<cv::Mat> outputs;
  73. net.forward(outputs, outputNames);
  74. auto time_3 = std::chrono::high_resolution_clock::now();
  75. // 检查输出是否有效
  76. if (outputs.empty() || outputs[0].empty())
  77. {
  78. throw std::runtime_error("模型前向传播未产生有效输出");
  79. }
  80. // 获取GAP层输出并转换为特征向量
  81. //cv::Mat featuresMat = outputs[0].reshape(1, 1);
  82. cv::Mat featuresMat = outputs[0];
  83. cv::normalize(featuresMat, featuresMat, 1.0, 0.0, cv::NORM_L2);
  84. // 转换为std::vector<float>
  85. std::vector<float> features(featuresMat.begin<float>(), featuresMat.end<float>());
  86. /*
  87. // 应用全局平均池化获取特征向量
  88. //std::vector<float> features = globalAveragePooling(outputs[0]);
  89. // L2归一化特征向量
  90. if (!features.empty())
  91. {
  92. float norm = std::sqrt(std::inner_product(features.begin(), features.end(), features.begin(), 0.0f));
  93. if (norm > 1e-6)
  94. {
  95. for (auto & val : features)
  96. {
  97. val /= norm;
  98. }
  99. }
  100. }*/
  101. auto time_4 = std::chrono::high_resolution_clock::now();
  102. auto duration_1 = std::chrono::duration_cast<std::chrono::milliseconds>(time_2 - time_1);
  103. std::wstring msg = L"图片处理完成,耗时: " + std::to_wstring(duration_1.count()) + L" 毫秒";
  104. DEBUG_LOG(msg.c_str());
  105. auto duration_2 = std::chrono::duration_cast<std::chrono::milliseconds>(time_3 - time_2);
  106. std::wstring msg2 = L"模型前向传播完成,耗时: " + std::to_wstring(duration_2.count()) + L" 毫秒";
  107. DEBUG_LOG(msg2.c_str());
  108. auto duration_3 = std::chrono::duration_cast<std::chrono::milliseconds>(time_4 - time_3);
  109. std::wstring msg3 = L"特征处理完成,耗时: " + std::to_wstring(duration_3.count()) + L" 毫秒";
  110. DEBUG_LOG(msg3.c_str());
  111. auto totalDuration = std::chrono::duration_cast<std::chrono::milliseconds>(time_4 - time_1);
  112. std::wstring msg4 = L"总耗时: " + std::to_wstring(totalDuration.count()) + L" 毫秒";
  113. DEBUG_LOG(msg4.c_str());
  114. return features;
  115. }
  116. catch (const std::exception & e)
  117. {
  118. std::string aa = std::string(e.what());
  119. DEBUG_LOG(("提取特征失败: " + std::string(e.what())).c_str());
  120. return {};
  121. }
  122. }
  123. std::vector<float> YoloFeatureExtractor::extractBackboneFeatures(const std::string & imagePath)
  124. {
  125. cv::Mat image = cv::imread(imagePath);
  126. if (image.empty())
  127. {
  128. throw std::runtime_error("Could not load image: " + imagePath);
  129. }
  130. cv::Mat blob;
  131. cv::dnn::blobFromImage(image, blob, 1.0 / 255.0, cv::Size(inputWidth, inputHeight), cv::Scalar(0, 0, 0), true, false);
  132. net.setInput(blob);
  133. std::vector<cv::String> layerNames = net.getLayerNames();
  134. std::vector<cv::String> backboneLayers;
  135. for (const auto & name : layerNames)
  136. {
  137. if (name.find("backbone") != std::string::npos ||
  138. name.find("conv") != std::string::npos ||
  139. name.find("stage") != std::string::npos)
  140. {
  141. backboneLayers.push_back(name);
  142. }
  143. }
  144. if (backboneLayers.empty())
  145. {
  146. backboneLayers.push_back(layerNames[layerNames.size() / 2]);
  147. }
  148. std::vector<cv::Mat> outputs;
  149. net.forward(outputs, backboneLayers);
  150. std::vector<float> features;
  151. for (size_t i = 0; i < outputs.size(); ++i)
  152. {
  153. cv::Mat output = outputs[i];
  154. features.reserve(features.size() + output.total());
  155. for (int j = 0; j < output.total(); ++j)
  156. {
  157. features.push_back(output.at<float>(j));
  158. }
  159. }
  160. return features;
  161. }
  162. std::vector<std::vector<float>> YoloFeatureExtractor::extractROIFeatures(const std::string & imagePath)
  163. {
  164. cv::Mat image = cv::imread(imagePath);
  165. if (image.empty())
  166. {
  167. throw std::runtime_error("Could not load image: " + imagePath);
  168. }
  169. cv::Mat blob;
  170. cv::dnn::blobFromImage(image, blob, 1.0 / 255.0, cv::Size(inputWidth, inputHeight), cv::Scalar(0, 0, 0), true, false);
  171. net.setInput(blob);
  172. std::vector<cv::Mat> outputs;
  173. net.forward(outputs, net.getUnconnectedOutLayersNames());
  174. const float CONFIDENCE_THRESHOLD = 0.5;
  175. const float NMS_THRESHOLD = 0.4;
  176. std::vector<int> classIds;
  177. std::vector<float> confidences;
  178. std::vector<cv::Rect> boxes;
  179. float x_factor = static_cast<float>(image.cols) / inputWidth;
  180. float y_factor = static_cast<float>(image.rows) / inputHeight;
  181. for (size_t outputIdx = 0; outputIdx < outputs.size(); ++outputIdx)
  182. {
  183. float * data = (float *)outputs[outputIdx].data;
  184. int rows = outputs[outputIdx].rows;
  185. int dimensions = outputs[outputIdx].cols;
  186. for (int i = 0; i < rows; ++i)
  187. {
  188. float objectness = data[4];
  189. if (objectness >= CONFIDENCE_THRESHOLD)
  190. {
  191. std::vector<float> probs;
  192. for (int c = 5; c < dimensions; ++c)
  193. {
  194. probs.push_back(data[c]);
  195. }
  196. int maxClassId = 0;
  197. float maxScore = probs[0];
  198. for (size_t p = 1; p < probs.size(); ++p)
  199. {
  200. if (probs[p] > maxScore)
  201. {
  202. maxScore = probs[p];
  203. maxClassId = static_cast<int>(p);
  204. }
  205. }
  206. if (maxScore > CONFIDENCE_THRESHOLD)
  207. {
  208. confidences.push_back(objectness * maxScore);
  209. classIds.push_back(maxClassId);
  210. float x = data[0];
  211. float y = data[1];
  212. float w = data[2];
  213. float h = data[3];
  214. int left = static_cast<int>((x - 0.5 * w) * x_factor);
  215. int top = static_cast<int>((y - 0.5 * h) * y_factor);
  216. int width = static_cast<int>(w * x_factor);
  217. int height = static_cast<int>(h * y_factor);
  218. boxes.push_back(cv::Rect(left, top, width, height));
  219. }
  220. }
  221. data += dimensions;
  222. }
  223. }
  224. std::vector<int> nms_result;
  225. cv::dnn::NMSBoxes(boxes, confidences, CONFIDENCE_THRESHOLD, NMS_THRESHOLD, nms_result);
  226. std::vector<std::vector<float>> roiFeatures;
  227. for (size_t i = 0; i < nms_result.size(); ++i)
  228. {
  229. int idx = nms_result[i];
  230. cv::Rect box = boxes[idx];
  231. box.x = std::max(0, std::min(box.x, image.cols - 1));
  232. box.y = std::max(0, std::min(box.y, image.rows - 1));
  233. box.width = std::max(0, std::min(box.width, image.cols - box.x));
  234. box.height = std::max(0, std::min(box.height, image.rows - box.y));
  235. std::vector<float> roiFeature;
  236. roiFeature.push_back(static_cast<float>(box.x) / image.cols);
  237. roiFeature.push_back(static_cast<float>(box.y) / image.rows);
  238. roiFeature.push_back(static_cast<float>(box.width) / image.cols);
  239. roiFeature.push_back(static_cast<float>(box.height) / image.rows);
  240. roiFeature.push_back(confidences[idx]);
  241. roiFeature.push_back(static_cast<float>(classIds[idx]));
  242. roiFeatures.push_back(roiFeature);
  243. }
  244. return roiFeatures;
  245. }