ITADN

move parameters to json file

#26Closedsbow 创建于 2024-11-13
enhancement
S
sbowcommented
Why: - dont have to recompile every time! - can define once - referance everywhere - unlocks variation of parameter experiments example, move "calibrations" to a json file like resolution in this snippet: ``` /******************************************************************************** * Function: create_input_video_stream * Description: Create an input video stream from the attached cameras. ********************************************************************************/ bool create_input_video_stream(void) { cap.open(0); // Open default webcam cap.set(cv::CAP_PROP_FRAME_WIDTH, 1280); cap.set(cv::CAP_PROP_FRAME_HEIGHT, 720); if (!cap.isOpened()) { std::cout << "Error: Could not open camera" << std::endl; return false; } return true; } ``` Use this: https://github.com/nlohmann/json Like this: 1st creat a "config" struct for use elsewhere in the program: ``` #include <nlohmann/json.hpp> #include <fstream> #include <iostream> struct Config { int frameWidth = 1280; int frameHeight = 720; // Method to load configuration from JSON file void loadFromFile(const std::string& fileName) { std::ifstream configFile(fileName); if (configFile) { nlohmann::json configJson; configFile >> configJson; // Use structured binding to iterate and assign values dynamically for (auto& [key, value] : configJson.items()) { if (key == "frame_width") frameWidth = value.get<int>(); else if (key == "frame_height") frameHeight = value.get<int>(); // Add more parameters here if needed } } else { std::cerr << "Could not open config file: " << fileName << std::endl; } } }; ``` then refer to it elsewhere like: ``` bool create_input_video_stream(const Config& config) { cap.open(0); cap.set(cv::CAP_PROP_FRAME_WIDTH, config.frameWidth); cap.set(cv::CAP_PROP_FRAME_HEIGHT, config.frameHeight); if (!cap.isOpened()) { std::cout << "Error: Could not open camera" << std::endl; return false; } return true; } int main() { Config config; config.loadFromFile("config.json"); create_input_video_stream(config); return 0; } ```
关闭于 2025-04-26 2 条评论