gpt4 book ai didi

c++ bmp to 2d-array 打印不切实际的值

转载 作者:行者123 更新时间:2023-11-28 05:33:43 25 4
gpt4 key购买 nike


我在做一个小项目时遇到了麻烦。我必须将 bmp 文件转换为二维颜色数组(我为每种颜色制作了自己的 typedef 结构)。该代码有效(它没有遇到任何错误)并且一些值与图像匹配但其他值不匹配;我图像的前 3 个像素都是白色的,而他说它们首先是红色,然后是绿色,最后是蓝色。

#include <string>
#include <iostream>
#include <fstream>

using namespace std;

const int W = 960, H = 720;

typedef struct Colors {
int red;
int green;
int blue;
} Color;


Color image[H][W];

void readBMP(char *filename) {
FILE *f = fopen(filename, "rb");
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header

// extract image height and width from header
int width = *(int *) &info[18];
int height = *(int *) &info[22];
/* W = width;
H = height;*/
int size = 3 * width * height;
unsigned char *data = new unsigned char[size]; // allocate 3 bytes per pixel
fread(data, sizeof(unsigned char), size, f); // read the rest of the data at once
fclose(f);
int index = 0;
for (int j = 0; j < H; j++) {
//cout << index << endl;
for (int k = 0; k < W; k++) {
index = (j * W) * 3 + k * 3;
Color c;
c.blue = (int) data[index];
c.green = (int) data[index + 1];
c.red = (int) data[index + 2];
//cout << "j/width: " << (j / width) << endl << "j%width: " << (j % width) << endl << endl;
image[j][k] = c;
cout << (image[j][k]).red << ' ' << (image[j][k]).green << ' ' << (image[j][k]).blue << endl;
}
}
}

int main() {
//std::cout << "this is a test function" << endl;
readBMP((char *) "test.bmp");
}

前50行的输出是:

255 0 0
255 0 0
255 0 0
0 0 0
0 0 0
71 66 255
128 115 82
40 245 194
30 184 96
133 32 21
64 1 235
19 51 51
102 102 128
102 64 38
160 6 102
9 153 153
215 10 60
92 36 3
0 50 143
0 0 0
0 0 0
0 0 0
4 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
107 152 191
105 150 189
104 149 188
105 150 189
104 149 188
100 145 184
97 141 180
96 140 179
96 138 176
96 138 176
98 137 176
99 138 177
101 140 179
103 142 181
106 144 183
106 145 184
111 150 189
106 148 186
107 149 187
105 147 185
104 143 182
112 151 190
...

提前致谢,贾里

最佳答案

这不是一个完整的位图解析器,它只能读取 24 位位图。它不会检查或读取位域位图或基于 clut 的位图。

最重要的是,这可能就是正在发生的事情。每次读取颜色时,32 位位图都会导致 channel 转移到下一个。这意味着大多数颜色在某种程度上都是不正确的。

您必须检查 header 中每个像素的位数 - 它是 header 中第 15 和第 16 个字节的 uint16_t。

但请注意,此解析器还有很多其他问题。

关于c++ bmp to 2d-array 打印不切实际的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38825306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com