這兩天需要封裝一個簡單處理圖片相關的DLL供Python/C#調用,因為CImg比較輕量級且易於集成,所以就決定是你了!CImg!
這篇隨筆記錄一下開發遇到的問題:
扔出網上翻來的入門PDF:
https://github.com/dtschump/CImg/blob/master/html/CImg_reference_chinese.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"); }