ZBLOG

读取图片,封装为函数 int numImages = 3; static const char* filenames[] = { "Data/img_test/6.第三面侧视图/100.bmp", "Data/img_test/6.第三面侧视图/101.bmp", "Data/img_test/6.第三面侧视图/102.bmp", //"Data/img_in/Image_5000.bmp", //"Data/img_in/Image_10000.bmp", ...

你可以将读取图像的代码封装为一个函数,使其更具模块化和可重用性。下面是如何实现这个功能的示例代码:

  1. #include <opencv2/opencv.hpp>
  2. #include <iostream>
  3. #include <vector>
  4. using namespace cv;
  5. using namespace std;
  6. // Function to read images from specified file paths
  7. void readImages(const vector<string>& filenames, vector<Mat>& images) {
  8. for (const auto& filename : filenames) {
  9. Mat im = imread(filename);
  10. if (im.empty()) {
  11. cout << "Could not read image: " << filename << endl;
  12. } else {
  13. images.push_back(im);
  14. }
  15. }
  16. }
  17. int main() {
  18. // Specify the number of images and their filenames
  19. int numImages = 3;
  20. vector<string> filenames = {
  21. "Data/img_test/6.第三面侧视图/100.bmp",
  22. "Data/img_test/6.第三面侧视图/101.bmp",
  23. "Data/img_test/6.第三面侧视图/102.bmp"
  24. // 可以在这里添加更多文件路径
  25. };
  26. vector<Mat> images;
  27. // Call the function to read images
  28. readImages(filenames, images);
  29. // 处理读取的图像(例如显示或进一步处理)
  30. return 0;
  31. }

代码说明:

  1. readImages 函数:接受一个字符串向量 filenames 和一个用于存储读取后图像的 images 向量。对于每个文件名,它尝试读取图像,并在成功时将其添加到 images 向量中。如果读取失败,则输出错误信息。

  2. 主函数 (main)

    • 定义了要读取的图片数量和文件名列表。
    • 调用 readImages 函数来读取这些图片。

这样,你就把原来的读图逻辑封装成了一个独立的函数,提高了代码的可读性和可维护性。你可以随时调用这个函数来读取不同路径下的图片,只需传递相应的文件名列表即可。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=21036

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?