使用python处理原始二进制图像数据

时间:2012-06-06 22:30:50

标签: python image image-processing python-imaging-library rgb

我有一个原始二进制图像存储为.bin文件,它有一些重要的数据。问题是颜色信息略有偏差所以我需要稍微改变一下。有没有什么方法可以让R&G和B值乘以标量,然后将其保存为原始二进制文件?

我希望使用python映像库来完成这项工作,因为我已经了解了图像模块的基础知识。我需要将每个像素乘以相同的值,但它将是R,G和B的不同值。我有以下代码打开文件,但后来我不知道该怎么做才能改变RGB值

fileName = raw_input("Enter a file name: ")

with open(fileName) as f:
    im = Image.fromstring('RGB', (3032, 2016), f.read())

如果您需要更多信息,请与我们联系。

更新

我编写了以下代码,它以我想要的方式转换图像,但它给了我一个错误。代码如下:

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)

我的错误是:

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

这可能是一种完全错误的编辑RGB值的方法,我知道它适用于JPEG而t可能只适用于JPEG,但这是我想做的。

2 个答案:

答案 0 :(得分:2)

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')

答案 1 :(得分:0)

您可能希望使用Python绑定或ImageMagick查看PIL

如果您只需读取文件并操纵二进制数据,请执行以下操作:

with open(filename, 'rb') as img:
   wrd=img.read(2)
   while wrd:
       # wrd == 2 bytes == your 16 bits...
相关问题