Reputation: 4419
I have an raw binary image stored as a .bin file and it has some important data on it. The problem is that the color information is slightly off so I need to alter it a little bit. Is there any way I can get in and multiply the R, G, and B values by a scalar and then save it back as a raw binary file?
I am hoping to use the python imaging library to do this as I already know the basics of the image module. I need to multiply every pixel by the same value but it will be a different value for R, G, and B. I have the following code to open the file but then I don't know what to do there to alter the RGB values.
fileName = raw_input("Enter a file name: ")
with open(fileName) as f:
im = Image.fromstring('RGB', (3032, 2016), f.read())
Let me know if you need any more information.
UPDATE:
I wrote the following code which is converting the image in a way that I would like but it gives me an error. The code is as follows:
with open(C:\Users\name\imagedata\visiblespec.bin, 'rb') as f:
im = Image.fromstring('RGB', (3032, 2016), f.read())
im = im.convert('RGB')
r, g, b = im.split()
r = r.point(lambda i: i * (255/171))
g = g.point(lambda i: i * (255/107))
b = b.point(lambda i: i * (255/157))
out = Image.merge('RGB', (r, g, b))
out.save(C:\Users\name\imagedata\visiblespecredone.bin)
and my error is this:
Traceback (most recent call last):
File "C:\Users\Patrick\workspace\colorCorrect\src\rawImage.py", line 18, in <module>
im = Image.fromstring('RGB', (3032, 2016), f.read())
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1797, in fromstring
im.fromstring(data, decoder_name, args)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 594, in fromstring
raise ValueError("not enough image data")
ValueError: not enough image data
This may be a completely wrong way to edit the RGB values, I know it works for a JPEG and t may only work for a JPEG but this is what I would like to do.
Upvotes: 3
Views: 5036
Reputation: 9437
import numpy as np
shape = (2016, 3032)
im = np.fromfile('visiblespec.bin', 'uint16').reshape(shape)
def tile(pattern, shape):
return np.tile(np.array(pattern, 'bool'), (shape[0] // 2, shape[1] // 2))
r = tile([[0, 0], [0, 1]], shape)
g = tile([[0, 1], [1, 0]], shape)
b = tile([[1, 0], [0, 0]], shape)
im = im.astype('float32')
im[r] *= 255 / 171.
im[g] *= 255 / 107.
im[b] *= 255 / 157.
np.rint(im, out=im)
np.clip(im, 0, 65535, out=im)
im = im.astype('uint16')
im.tofile('visiblespecredone.bin')
Upvotes: 2
Reputation: 103694
You might want to look at ImageMagick with the Python bindings or PIL.
If you just need to read the file and manipulate the binary data, do something like:
with open(filename, 'rb') as img:
wrd=img.read(2)
while wrd:
# wrd == 2 bytes == your 16 bits...
Upvotes: 0