C++ 从值数组中保存图像的快速方法

标签 c++ opencv image-processing bitmap cimg

现在,我正在使用 CImg。 由于this,我无法使用OpenCV问题。

我的 CImg 代码如下所示:

cimg_library::CImg<float> img(512,512); 
cimg_forXYC(img,x,y,c) { img(x,y,c) = (array[x][y]); } //array contains all float values between 0/1
img.save(save.c_str()); //taking a  lot of time

通过使用时钟,我能够确定第一步,for 循环需要 0-0.01 秒。然而,第二步,即保存图像,需要 0.06 秒,由于我拥有的图像数量,这个时间太长了。

我正在另存为位图。 在 C++ 中是否有更快的方法来完成相同的事情(从值数组创建图像并保存)?

最佳答案

这是一个小函数,可以将您的图像保存在 pgm format 中,大多数东西都可以读取并且非常简单。它要求您的编译器支持 C++11,大多数编译器都支持 C++11。它还被硬编码为 512x512 图像。

#include <fstream>
#include <string>
#include <cmath>
#include <cstdint>

void save_image(const ::std::string &name, float img_vals[][512])
{
   using ::std::string;
   using ::std::ios;
   using ::std::ofstream;
   typedef unsigned char pixval_t;
   auto float_to_pixval = [](float img_val) -> pixval_t {
      int tmpval = static_cast<int>(::std::floor(256 * img_val));
      if (tmpval < 0) {
         return 0u;
      } else if (tmpval > 255) {
         return 255u;
      } else {
         return tmpval & 0xffu;
      }
   };
   auto as_pgm = [](const string &name) -> string {
      if (! ((name.length() >= 4)
             && (name.substr(name.length() - 4, 4) == ".pgm")))
      {
         return name + ".pgm";
      } else {
         return name;
      }
   };

   ofstream out(as_pgm(name), ios::binary | ios::out | ios::trunc);

   out << "P5\n512 512\n255\n";
   for (int x = 0; x < 512; ++x) {
      for (int y = 0; y < 512; ++y) {
         const pixval_t pixval = float_to_pixval(img_vals[x][y]);
         const char outpv = static_cast<const char>(pixval);
         out.write(&outpv, 1);
      }
   }
}

关于C++ 从值数组中保存图像的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44502079/

相关文章:

c++ - 未解析的外部符号虽然它已经被定义

java - 在 Javacv 中传递 Point2f [] 作为 getAffineTransform() 的参数

c++ - 带有 C++ 插件的 Node 应用程序在运行时提示 undefined symbol

c++ - 图像的逐行像素检查

c++ - 编译空文件是否遵循 C++ 标准?

c++ - 如何使用 C++ 在 CSV 文件上执行逐行操作(一些 x)

c++ - Qt中的弹出菜单事件控件

java 内存溢出错误 : memory usage is too high: physicalBytes > maxPhysicalBytes javacpp Pointer deallocator()

c++ - 二维阵列两个方向之间的性能测试

python - 对于大于 3 x 3 的尺寸,OpenCV 的 Sobel 滤波器的核系数是多少?