I'm trying to read a .bmp
file with c++ and save the grey values (average over RGB values) normalized into a vector under Ubuntu 14.04. Somehow the values of the vector end up completely wrong. Can you imagine why?
std::vector<double> readBMP(const char* filename, int* width, int* height){
std::vector<double> bmp;
FILE* f = fopen(filename, "rb");
if(f == NULL){
std::cerr << "file not found!" << std::endl;
std::vector<double> empty;
width = NULL;
height = NULL;
return empty;
}
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header
// extract image height and width from header
*width = *(int*)&info[18];
*height = *(int*)&info[22];
int data_offset = *(int*)(&info[0x0A]);
fseek(f, (long int)(data_offset - 54), SEEK_CUR);
int row_padded = (*width*3 + 3) & (~3);
unsigned char* data = new unsigned char[row_padded];
unsigned char tmp;
for(int i = 0; i < *height; i++)
{
fread(data, sizeof(unsigned char), row_padded, f);
for(int j = 0; j < *width*3; j += 3)
{
// Convert (B, G, R) to (R, G, B)
tmp = data[j];
data[j] = data[j+2];
data[j+2] = tmp;
bmp.push_back(((double)data[j]+(double)data[j+1]+(double)data[j+2])/(3*255));
std::cout << "R: "<< (int)data[j] << " G: " << (int)data[j+1]<< " B: " << (int)data[j+2]<< std::endl;
}
}
return bmp;
}
I print the rgb values, and checked it with an example image, which has four pixels:
black | black | black
---------------------
grey | grey | grey
---------------------
white | white | white
The expected output should be (it's reversed):
R: 255 G: 255 B: 255
R: 255 G: 255 B: 255
R: 255 G: 255 B: 255
R: 128 G: 128 B: 128
R: 128 G: 128 B: 128
R: 128 G: 128 B: 128
R: 0 G: 0 B: 0
R: 0 G: 0 B: 0
R: 0 G: 0 B: 0
but it is:
R: 255 G: 255 B: 255
R: 255 G: 255 B: 255
R: 255 G: 255 B: 255
R: 128 G: 128 B: 255
R: 128 G: 255 B: 128
R: 255 G: 128 B: 128
R: 0 G: 0 B: 255
R: 0 G: 255 B: 0
R: 255 G: 0 B: 0
Note: The code is a modified version of an answer of this question: read pixel value in bmp file