4

基本上我想要做的是获取一个文件,将其二进制数据(当然是十进制)放入一个列表中,然后基于该列表使用 PIL 生成一个灰度位图图像。

例如,如果文件是 5000 字节(图像大小为 100 x 50)并且每个字节是 0 到 255 之间的整数,我想将第一个字节绘制到第一个像素并沿着行向下直到所有字节都用完。

到目前为止,我唯一得到的就是读取文件:

f = open(file, 'rb')
text = f.read()
for s in text:
    print(s)

这以十进制输出字节。

我正在寻找一些关于如何实现这一目标的方向。我做了很多搜索,但似乎没有太多人尝试过我想做的事情。

任何帮助将不胜感激!

4

4 回答 4

4

您可以使用 Numpyfromfile()来有效地阅读它:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Define width and height
w, h = 50, 100

# Read file using numpy "fromfile()"
with open('data.bin', mode='rb') as f:
    d = np.fromfile(f,dtype=np.uint8,count=w*h).reshape(h,w)

# Make into PIL Image and save
PILimage = Image.fromarray(d)
PILimage.save('result.png')

关键词:PIL、Pillow、Python、Numpy、读取原始数据、二进制、8 位、灰度灰度、图像、图像处理。

于 2019-05-09T15:57:18.880 回答
3

来自PIL Image 文档

Image.fromstring(mode, size, data)

对于您的示例:

im = Image.fromstring('L', (100, 50), text)

还有一个frombuffer功能,但区别不明显。

于 2012-05-26T04:00:00.180 回答
3

我认为应该这样做。是scipy一种选择吗?

In [34]: f = open('image.bin', 'r')

In [35]: Y = scipy.zeros((100, 50))

In [38]: for i in range(100):
             for j in range(50):
                 Y[i,j] = ord(f.read(1))

In [39]: scipy.misc.imsave('image.bmp', Y)
于 2012-05-26T03:47:24.630 回答
2

I don't think using PIL for this would be incredibly efficient, but you can look into the ImageDraw module if you are looking to paint onto a blank canvas.

My approach would be a bit different: since your file format resembles the Netpbm format very closely, I would try converting it. For simplicity, try adding/manipulating the headers of your format while reading it so that PIL can read it natively.

于 2012-05-26T03:11:23.167 回答