这两天需要封装一个简单处理图片相关的DLL供Python/C#调用,因为CImg比较轻量级且易于集成,所以就决定是你了!CImg!
这篇随笔记录一下开发遇到的问题:
扔出网上翻来的入门PDF:
Q.关于CImg 获取 Stride的问题:
目前没有找到相关函数,只能自己封装一下:
int __stdcall Stride(int wid, int spectrum)
{
int ret = spectrum * wid;
if (ret % 4 != 0)
{
ret = ret + (4 - ret % 4);
}
std::cout << "stride : " << ret << std::endl;
return ret;
}
使用示例代码段:
CImg<unsigned char> img_dest(800, 600, 1, 3);
Stride(img_dest.width(), img_dest.spectrum());
Q.关于CImg 像素数据存储格式的问题:
CImg存储像素点的格式不太同于我常用的图形库....采用的是非交错格式存储,那什么是非交错存储格式捏:
官方解释:http://cimg.eu/reference/group__cimg__storage.html
我朝网友解释:https://www.cnblogs.com/Leo_wl/p/3267638.html#_label0
老王网友解释:https://www.codefull.net/2014/11/cimg-does-not-store-pixels-in-the-interleaved-format/
我的大概概念说明:
以RGB为例,像素点 rgb(0,0),rgb(0,1),rgb(0,2)
交错(interleaved)格式存储:内存数组存储顺序为:[R1, G1, B1 ,R2, G2, B2 ,R3, G3, B3];
非交错格式存储:内存数组存储顺序为:[R1, R2, R3 ,G1, G2, G3 ,B1, B2, B3];
OpenGL/DX/Qt的QImage Net的 BitmapData的像素数据都是交错模式存储(RGB为例).
而CImg中的存储却采用的非交错格式
Q.怎么样将CImg改成按交错模式进行像素格式存储数据呢?
Note:调用permute_axes函数之后,会重置Width/Height/相关数据信息,如果需要原始数据请在调用permute_axes前获取,如例子
void TestFunc()
{
CImg<unsigned char> image("d://test1.jpg");
int rgb_leng = image.width()*image.height();
unsigned char *ptest = new unsigned char[rgb_leng * 3];
int width = image.width();
int height = image.height();
image.permute_axes("cxyz");
unsigned char *ptr = image.data(0, 0);
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
unsigned char r = ptr[i * j * 3 + 0];
unsigned char g = ptr[i * j * 3 + 1];
unsigned char b = ptr[i * j * 3 + 2];
//r
ptest[ i * width + j ] = ptr[ i * j * 3 + 0 ];
//g
ptest[ i * width + j + rgb_leng ] = ptr[ i * j * 3 + 1 ];
//b
ptest[ i * width + j + rgb_leng * 2] = ptr[ i * j * 3 + 2 ];
std::cout << "(r: " << (int)r
<< " g: " << (int)g
<< " b: " << (int)b << ")";
}
}
image.permute_axes("yzcx");
CImg<unsigned char> imtest(ptest, width, height, 1, 3);
std::cout << "size of iamge :" << image.size() << std::endl;
std::cout << "size of copy iamge :" << imtest.size() << std::endl;
imtest.save("d://convert.jpg");
image.display("test");
}