C ++从数组值中快速保存图像的方法 [英] C++ fast way to save image from array of values
问题描述
现在,我正在使用CImg。
由于这个问题我无法使用OpenCV 。
Right now, I am using CImg. I am unable to use OpenCV due to this issue.
我的CImg代码如下所示:
My CImg code looks like this:
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秒,由于我拥有的图像数量太长,这样做太长了。
By using clocks I was able to determine that the first step, the for loop takes 0-0.01 seconds. However, the second step, the saving of the image, takes 0.06 seconds, which is way too long due to the amount of images I have.
我保存为位图。
有没有更快的方法在C ++中完成相同的事情(从值数组创建图像并保存)?
I am saving as bitmaps. Is there any faster way to accomplish the same things (creating an image from an array of values and save) in C++?
推荐答案
这是一个小功能,可以用 pgm格式保存您的图像,大多数事情都可以阅读,并且很简单。它需要你的编译器支持C ++ 11,大多数都支持。它也被硬编码为512x512图像。
Here is a small function that will save your image in pgm format, which most things can read and is dead simple. It requires your compiler support C++11, which most do. It's also hard-coded to 512x512 images.
#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 ++从数组值中快速保存图像的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!