私がやっている小さなプロジェクトに問題があります。 bmpファイルをColorの2次元配列に変換する必要があります(私は各色ごとに独自のtypedef構造体を作成しました)。 コードは機能し(エラーにはならず)、一部の値はイメージと一致しますが、他の値は一致しません。私のイメージの最初の3つのピクセルはすべて白で、最初は赤、次に緑、最後に青です。C++ bmp to 2d-arrayは非現実的な値を出力します
#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
...
おかげで、 ヤリ