【问题标题】:Getting the pixel value of BMP file获取BMP文件的像素值
【发布时间】:2009-12-28 08:35:53
【问题描述】:

我有一个关于阅读 bmp 图像的问题。如何获取 bmp 图像中的像素值(R、G、B 值)? 谁能帮我使用 C 编程语言?

【问题讨论】:

    标签: c pixel bmp


    【解决方案1】:

    注意:如果您的 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);
    

    ~洛科图斯

    【讨论】:

    • 在点击图像数据之前是否需要通过标头块?
    • @Anon 如果我的文件是 jpeg 怎么办?
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      您需要学习 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 的标头以了解有关格式的更多信息。

      【讨论】:

        猜你喜欢
        • 2013-04-10
        • 1970-01-01
        • 2012-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多