不确定为什么要将 CImg 结构/类中的所有数据复制到另一个 2D 数组中,但无论如何都可以访问它。因此,如果您想要位置 [x,y] 的像素,只需使用:
img(x,y)
这是一个转储图像的完整程序 - 访问内部循环中的单个像素:
#include <iostream>
#include <cstdlib>
#define cimg_display 0
#include "CImg.h"
using namespace cimg_library;
using namespace std;
int main() {
CImg<unsigned char> img("test.pgm");
// Get width, height, number of channels
int w=img.width();
int h=img.height();
int c=img.spectrum();
cout << "Dimensions: " << w << "x" << h << " " << c << " channels" <<endl;
// Dump all pixels
for(int y=0;y<h;y++){
for(int x=0;x<w;x++){
cout << y << "," << x << " " << (int)img(x,y) << endl;
}
}
}
我使用了这张测试图像 - 它是 5x3 PGM(便携式灰度图),因此您可以轻松查看像素值,但它与 PNG 图像相同:
P2
5 3
255
0 1 2 3 4
10 11 12 13 14
100 101 102 103 104
这是输出,你可以看到与图像匹配:
Dimensions: 5x3 1 channels
0,0 0
0,1 1
0,2 2
0,3 3
0,4 4
1,0 10
1,1 11
1,2 12
1,3 13
1,4 14
2,0 100
2,1 101
2,2 102
2,3 103
2,4 104