How to convert 24 bit RGB array into an image?

帅比萌擦擦* 提交于 2019-12-20 05:45:57

问题


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 array to an image, I can easily verify my result. Expecting your help for the same. Please.

Example: 4x3 Resolution Image, I have following data as text file.

110000001100000011000000 110000001100000011111111 110000001100000011111111 110000001100000011111111 110000001100000011111111 110000001100000011111111 110000001100000011000000 110000001100000011111111 110000001100000011111111 110000001100000011111111 110000001100000011111111 110000001100000011111111


回答1:


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:

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.



来源:https://stackoverflow.com/questions/28273627/how-to-convert-24-bit-rgb-array-into-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!