Reputation: 739
I have been searching google for the method to display a raw image data using python libraries but couldn't find any proper solution. The data is taken from a camera module and it has the '.raw' extension. Also when I tried to open it in the terminal via 'more filename.raw', the console said that this is a binary file. Vendor told me that the camera outputs 16-bits raw greyscale data.
But I wonder how I can display this data via PIL, Pillow or just Numpy. I have tested the PIL's Image module. However, it couldn't identify the image data file. It seems the PIL doesn't consider the .raw file as an image data format. BMP files could be displayed, but this '.raw' couldn't.
Also when I tried with just read function and matplotlib, like the followings
from matplotlib import pyplot as plt
f = open("filename.raw", "rb").read()
plt.imshow(f)
plt.show()
then an error occurs with
ERROR: Image data can not convert to float
Any idea will be appreciated.
link: camera module
I made some improvement with the following codes. But now the issue is that this code displays only some portion of the entire image.
from matplotlib import pyplot as plt
import numpy as np
from StringIO import StringIO
from PIL import *
scene_infile = open('G0_E3.raw','rb')
scene_image_array = np.fromfile(scene_infile,dtype=np.uint8,count=1280*720)
scene_image = Image.frombuffer("I",[1280,720],
scene_image_array.astype('I'),
'raw','I',0,1)
plt.imshow(scene_image)
plt.show()
Upvotes: 18
Views: 79496
Reputation: 117
import numpy as np
from PIL import Image
import rawpy
# For Adobe DNG image
input_file = 'path/to/rawimage.dng'
rawimg = rawpy.imread(input_file)
npimg = rawimg.raw_image
# For raw image (without any headers)
input_file = 'path/to/rawimage.raw'
npimg = np.fromfile(input_file, dtype=np.uint16)
imageSize = (3648, 2736)
npimg = npimg.reshape(imageSize)
# Save the image from array to file.
# TIFF is more suitable for 4 channel 10bit image
# comparing to JPEG
output_file = 'out.tiff'
Image.fromarray(npimg/1023.0).save(output_file)
Upvotes: 5
Reputation: 3500
Have a look at rawpy:
import rawpy
import imageio
path = 'image.raw'
raw = rawpy.imread(path)
rgb = raw.postprocess()
imageio.imsave('default.tiff', rgb)
rgb
is just an RGB numpy array, so you can use any library (not just imageio
) to save it to disk.
If you want to access the unprocessed Bayer data, then do:
bayer = raw.raw_image
See also the API docs.
Upvotes: 21