How to convert 24 bit RGB array into an image?

后端 未结 1 1161
鱼传尺愫
鱼传尺愫 2021-01-26 05:59

My program result is giving 24 bit RGB data. It is very difficult verify my result by looking into the array of 24 bit data.

If there is any easy method to convert this

相关标签:
1条回答
  • 2021-01-26 06:36

    I had a look at this and it is pretty ugly but works - I think. I use awk to convert the ones and zeroes into straight numbers, and lay them out in a PPM format file which is about the simplest file format you can get from the NetPBM suite documentation here.

    So, for a 4x3 image with RGB and 255 as the maximum pixel intensity, your file will need to look like this:

    P3     # header saying PPM format
    4 3    # 4x3 pixels
    255    # max value per pixel is 255
    192    # Red value of top left pixel
    192    # Green value of top left pixel
    192    # Blue vaue of top left pixel
    ...
    ...
    

    So, I convert your file like this

    #!/bin/bash
    tr ' ' '\n' < file | awk '
       function bintxt2num(str){
          result=0;
          this=1;
          for(i=8;i>0;i--){
             if(substr(str,i,1)=="1")result += this
             this*=2
          }
          print result
       }
       BEGIN{ printf "P3\n4 3\n255\n"}
       {
          R=substr($0,1,8);  bintxt2num(R);
          G=substr($0,9,8);  bintxt2num(G);
          B=substr($0,17,8); bintxt2num(B);
       }' | convert ppm:- -scale 5000% result.png
    

    And at the end, I use the ImageMagick tool convert to convert the PPM file output from awk into a PNG file called result.png and scale it up to a decent size while I am at it.

    It looks like this:

    enter image description here

    In case I have made a silly mistake somewhere in my awk, your PPM file comes out looking like this:

    P3
    4 3
    255
    192
    192
    192
    192
    192
    255
    192
    192
    255
    192
    192
    255
    192
    192
    255
    192
    192
    255
    192
    192
    192
    192
    192
    255
    192
    192
    255
    192
    192
    255
    192
    192
    255
    192
    192
    255
    

    If you object to, or cannot install ImageMagick for some reason, you can always use the original NetPBM binaries and run ppm2tiff or ppm2jpeg to do the conversion from PPM to TIFF or JPEG. See here.

    0 讨论(0)
提交回复
热议问题