utils.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma once
  2. #include <opencv2/opencv.hpp>
  3. #include <dirent.h>
  4. #include <fstream>
  5. static inline cv::Mat preprocess_img(cv::Mat& img, int input_w, int input_h) {
  6. int w, h, x, y;
  7. float r_w = input_w / (img.cols*1.0);
  8. float r_h = input_h / (img.rows*1.0);
  9. if (r_h > r_w) {
  10. w = input_w;
  11. h = r_w * img.rows;
  12. x = 0;
  13. y = (input_h - h) / 2;
  14. } else {
  15. w = r_h * img.cols;
  16. h = input_h;
  17. x = (input_w - w) / 2;
  18. y = 0;
  19. }
  20. cv::Mat re(h, w, CV_8UC3);
  21. cv::resize(img, re, re.size(), 0, 0, cv::INTER_LINEAR);
  22. cv::Mat out(input_h, input_w, CV_8UC3, cv::Scalar(128, 128, 128));
  23. re.copyTo(out(cv::Rect(x, y, re.cols, re.rows)));
  24. return out;
  25. }
  26. static inline int read_files_in_dir(const char *p_dir_name, std::vector<std::string> &file_names) {
  27. DIR *p_dir = opendir(p_dir_name);
  28. if (p_dir == nullptr) {
  29. return -1;
  30. }
  31. struct dirent* p_file = nullptr;
  32. while ((p_file = readdir(p_dir)) != nullptr) {
  33. if (strcmp(p_file->d_name, ".") != 0 &&
  34. strcmp(p_file->d_name, "..") != 0) {
  35. //std::string cur_file_name(p_dir_name);
  36. //cur_file_name += "/";
  37. //cur_file_name += p_file->d_name;
  38. std::string cur_file_name(p_file->d_name);
  39. file_names.push_back(cur_file_name);
  40. }
  41. }
  42. closedir(p_dir);
  43. return 0;
  44. }
  45. // Function to trim leading and trailing whitespace from a string
  46. static inline std::string trim_leading_whitespace(const std::string& str) {
  47. size_t first = str.find_first_not_of(' ');
  48. if (std::string::npos == first) {
  49. return str;
  50. }
  51. size_t last = str.find_last_not_of(' ');
  52. return str.substr(first, (last - first + 1));
  53. }
  54. // Src: https://stackoverflow.com/questions/16605967
  55. static inline std::string to_string_with_precision(const float a_value, const int n = 2) {
  56. std::ostringstream out;
  57. out.precision(n);
  58. out << std::fixed << a_value;
  59. return out.str();
  60. }
  61. static inline int read_labels(const std::string labels_filename, std::unordered_map<int, std::string>& labels_map) {
  62. std::ifstream file(labels_filename);
  63. // Read each line of the file
  64. std::string line;
  65. int index = 0;
  66. while (std::getline(file, line)) {
  67. // Strip the line of any leading or trailing whitespace
  68. line = trim_leading_whitespace(line);
  69. // Add the stripped line to the labels_map, using the loop index as the key
  70. labels_map[index] = line;
  71. index++;
  72. }
  73. // Close the file
  74. file.close();
  75. return 0;
  76. }