现在,我正在使用 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/