获取BMP文件的像素值

use*_*468 6 c pixel bmp

我有一个关于读取bmp图像的问题.如何获取bmp图像中的像素值(R,G,B值)?任何人都可以帮我使用C编程语言吗?

小智 12

注意:如果您的BMP具有Alpha通道,则可能需要为alpha值获取额外的字节.在那种情况下,图像将是image[pixelcount][4],并且您将添加另一getc(streamIn)行来保存第四个索引.我的BMP结果证明不需要那样做.

 // super-simplified BMP read algorithm to pull out RGB data
 // read image for coloring scheme
 int image[1024][3]; // first number here is 1024 pixels in my image, 3 is for RGB values
 FILE *streamIn;
 streamIn = fopen("./mybitmap.bmp", "r");
 if (streamIn == (FILE *)0){
   printf("File opening error ocurred. Exiting program.\n");
   exit(0);
 }

 int byte;
 int count = 0;
 for(i=0;i<54;i++) byte = getc(streamIn);  // strip out BMP header

 for(i=0;i<1024;i++){    // foreach pixel
    image[i][2] = getc(streamIn);  // use BMP 24bit with no alpha channel
    image[i][1] = getc(streamIn);  // BMP uses BGR but we want RGB, grab byte-by-byte
    image[i][0] = getc(streamIn);  // reverse-order array indexing fixes RGB issue...
    printf("pixel %d : [%d,%d,%d]\n",i+1,image[i][0],image[i][1],image[i][2]);
 }

 fclose(streamIn);
Run Code Online (Sandbox Code Playgroud)

〜Locutus


Ada*_*ers 8

简单的方法是为您选择的平台找到一个好的图像处理库并使用它.

困难的方法是打开文件并实际解释其中的二进制数据.为此,您需要BMP文件规范.我建议先尝试一下简单的方法.


Mad*_*dhu 7

您需要研究BMP文件格式.读取未压缩的24位BMP文件更容易.它们只包含开头的标题和每个像素的RGB值.

首先,请在http://en.wikipedia.org/wiki/BMP_file_format上查看2x2位图图像的示例.请按照以下步骤操作.

  1. 创建Wikipedia上显示的2x2 BMP图像.
  2. 使用C程序以二进制模式打开文件.
  3. 寻找字节位置54.
  4. 读3个字节.

字节分别为0,0和255.(不确定订单是否为RGB.我已经做了这么久,我认为订单不是RGB.只需验证这一点.)

就如此容易!研究BMP的标题以了解有关格式的更多信息.