Search code examples
rimagebinaryfiles

R - Cannot correctly display grayscale image from binary file


I want to display a grayscale image stored as a binary file. I tried the image and RasterImage functions, but the output looks of less quality than the original's. Here is an example of my code:

finfo=file.info("image_file")

toread= file("image_file","rb")

image_data = readBin(toread, integer(), size=1, n = finfo$size, endian="little")

img_m<-matrix(image_data,nrow=480,ncol=640)

image(data_m,axes=FALSE,col=grey(seq(0,1,length=256)))

The ouput of the code above looks like this:

enter image description here

Howerver, the original image looks like this:

enter image description here

I tried the same with Python, using the Image.frombytes function and it displays the image correctly. I haven't been able to do the same with R.

UPDATE: I set the first 150,000 pixels to 0 just to see if it would affect correctly the display and instead of black pixels I got gray pixels. Here is the image:

enter image description here

Does anybody know the right function to display it correctly, or what is missing in my code to get the right image?

I appreciate any insight on this.


Solution

  • I changed two main things to solve this. The first is that using integer() as the what parameter in the readBin() causes the binary file to be read as a vector of signed integers. Thus, the obtained vector contained negative values, which affected the grayscale. To solve this, I used raw() as the what argument and then converted the vector to integer with as.integer().

    The second change is that I used the rasterImage() function instead of the image() function to display the image, since the former function outputs an image with higher contrast than the original.