我有一个 BMP 格式图像,按以下方式存档
for (j = 0; j < 240; j++) {
for(i=0;i<320;i++) {
data_temp = LCD_ReadRAM();
image_buf[i*2+1] = (data_temp&0xff00) >> 8;
image_buf[i*2+0] = data_temp & 0x00ff;
}
ret = f_write(&file, image_buf, 640, &bw);
其中 LCD_ReadRam 函数从 LCD 屏幕一次读取一个像素
我想知道,如何获取该图像文件的像素位置。
以及如何将每个像素的值保存在[320][240]矩阵中
任何帮助将不胜感激,谢谢。
最佳答案
BMP 文件阅读器可以满足您的需求。您可以获得任何好的 BMP 文件阅读器并根据您的目的进行调整。例如:this question and answer给出了假定 24 位 BMP 格式的 BMP 文件读取器。您的格式是 16 位,因此需要进行一些调整。
这是我这样做的尝试(没有测试,所以你应该对硬编码的细节持保留态度)。
int i;
FILE* f = fopen(filename, "rb");
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header
int width = 320, height = 240; // might want to extract that info from BMP header instead
int size_in_file = 2 * width * height;
unsigned char* data_from_file = new unsigned char[size_in_file];
fread(data_from_file, sizeof(unsigned char), size_in_file, f); // read the rest
fclose(f);
unsigned char pixels[240 * 320][3];
for(i = 0; i < width * height; ++i)
{
unsigned char temp0 = data_from_file[i * 2 + 0];
unsigned char temp1 = data_from_file[i * 2 + 1];
unsigned pixel_data = temp1 << 8 | temp0;
// Extract red, green and blue components from the 16 bits
pixels[i][0] = pixel_data >> 11;
pixels[i][1] = (pixel_data >> 5) & 0x3f;
pixels[i][2] = pixel_data & 0x1f;
}
注意:这假设您的 LCD_ReadRAM
函数(大概是从 LCD 内存中读取内容)给出标准 5-6-5 格式的像素。
名称 5-6-5 表示为每个颜色分量(红、绿、蓝)分配的每个 16 位数字中的位数。还存在其他分配,例如 5-5-5 ,但我从未在实践中见过它们。
关于c - BMP 16位图像转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17858581/