目的是对一维数组进行编程,为每个 x,y 位置索引 3 个 channel 值。数据是 3 channel 图像。
存储这些数据的最佳方式是什么?索引方案是什么?我如何访问每个 x,y 的每个 rgb?
它需要位于一个数组中,因为这是我正在使用的函数的输入。
最佳答案
您可以通过应用以下内容快速计算一维数组的索引...
index = image_width * channel_count * column_offset + row_offset * channel_count
当然,数学可以优化,但它可以帮助您入门。
假设我创建了一个 RGB 数据
convert -size 3x3 gradient:yellow-blue -depth 8 rgb:- | hexdump
0000000 ff ff 00 ff ff 00 ff ff 00 80 80 80 80 80 80 80
0000010 80 80 00 00 ff 00 00 ff 00 00 ff
000001b
我可以按索引打印出每个像素的 RGB 值
#include <stdio.h>
int main(int argc, const char * argv[]) {
unsigned char blob[0x1b] = {
0xff, 0xff, 0x00, 0xff, 0xff, 0x00, 0xff, 0xff, 0x00,
0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff
};
size_t x,y,w,h, index;
for (y=0, h=3; y<h; y++) { // Rows
for (x=0, w=3; x<w; x++) { // Columns
// Get pixel at (x,y)
index = w * 3 * y + x * 3;
printf("%02zu: #%02x%02x%02x\n",
index,
blob[index+0], // Red
blob[index+1], // Green
blob[index+2]); // Blue
}
}
return 0;
}
哪些输出
00: #ffff00
03: #ffff00
06: #ffff00
09: #808080
12: #808080
15: #808080
18: #0000ff
21: #0000ff
24: #0000ff
关于c - 如何在数组中存储 RGB 图像并在 C 中按 x,y 对其进行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33045106/