我需要读取灰度png图像,以便将像素值(0-255)存储在无符号字符的2D矩阵中。 目前,我正在C ++中使用CImg,它可以成功读取图像,但是我无法弄清楚如何从CImg容器中提取像素数据。
我可以这样做:
CImg<unsigned char> image("img1.png");
unsigned char* img1 = image.data();
但是它给了我一个char *,根据文档,它是“指向图像第一个值的指针”,但是我不知道该怎么做,或者如何访问其他值。
关于此的任何提示吗?
谢谢你, 大卫
答案 0 :(得分:0)
确实有很多可能性。
您可以使用当前的方法,并仅遍历原始像素数组:
CImg<unsigned char> image("img1.png");
unsigned char* img1 = image.data();
for(int i=0; i < image.size(); i++) {
logger_->info("*img1 value: {}", *(img1+i));
}
根据docs:
Size()返回width()* height()* depth()* spectrum(),即图像实例的像素缓冲区中类型T的值总数
因此,您也可以直接使用以下尺寸:
喜欢这个:
CImg<unsigned char> image("img1.png");
unsigned char* img1 = image.data();
for(int i=0; i < image.width()*image.height()*image.depth()*image.spectrum(); i++) {
logger_->info("*img1 value: {}", *(img1+i));
}
当然可以使用它编写分别遍历每个维度的嵌套循环。
如果您不想遍历原始数组,可以使用迭代器:
CImg<unsigned char> image("img1.png");
unsigned char* img1 = image.data();
for (CImg<unsigned char>::iterator it = image.begin(); it < image.end(); ++it) {
logger_->info("it value: {}", *it);
}
或者,如果您想尝试其他方法,请查阅文档,我提供的示例并不详尽。
答案 1 :(得分:0)
不确定为什么要以完全一样的方式访问它时,为什么要将所有数据从 CImg 结构/类复制到另一个2D数组中。因此,如果您希望像素位于[x,y]位置,请使用:
.data
buffer BYTE 21 DUP(0) ; input buffer
byteCount DWORD ? ; holds counter
.code
mov edx,OFFSET buffer ; point to the buffer
mov ecx,SIZEOF buffer ; specify max characters
call ReadString ; input the string
mov byteCount,eax ; number of characters
这里是转储图像的完整程序-访问内部循环中的各个像素:
img(x,y)
我使用了此测试图像-它是5x3 PGM(便携式灰度图),因此您可以轻松查看像素值,但与PNG图像相同:
#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;
}
}
}
这是输出,您可以看到它与图像匹配:
P2
5 3
255
0 1 2 3 4
10 11 12 13 14
100 101 102 103 104