使用PIL将二进制字符串转换为图像

时间:2014-06-17 17:18:24

标签: python image python-2.7 binary python-imaging-library

所以,我想要做的就是让PIL根据二进制字符串创建一个图像。 一些背景故事:

from PIL import Image

value = "0110100001100101011011000110110001101111"
vdiv = [value[i:i+8] for i in range(0, len(value), 8)]

^这将从二进制字符串中创建一个字节列表。 ['01101000', '01100101',.....]

def diff(inp):
    if inp == '1':
        return (0,0,0)
    if inp == '0':
        return (255,255,255)
    else:
        pass

^这会返回每个相应位的颜色元组,如果我调用:

for i in vdiv:
    for i2 in i:
        print diff(i2)

它将为列出的字节中的每个位打印每个颜色元组。 (0,0,0) (0,0,0) (255,255,255)...

我想知道的是,如何让PIL创建像素与二进制字符串匹配的图像?

以下是它的样子。screenshot

到目前为止我对PIL的看法:

img = Image.new( 'RGB', (8,len(vdiv)), "white")
pixels = img.load()

##
for x in range(img.size[0]):
    for y in range(img.size[1]):
        for i in vdiv:
            for i2 in i:
                pixels[x,y] = diff(i2) #Creates a black image. What do?
##

img.show()

for x in range位得到了我。我迷路了。

2 个答案:

答案 0 :(得分:1)

您可以使用img.putdata

import Image

value = "0110100001100101011011000110110001101111"

cmap = {'0': (255,255,255),
        '1': (0,0,0)}

data = [cmap[letter] for letter in value]
img = Image.new('RGB', (8, len(value)//8), "white")
img.putdata(data)
img.show()        

enter image description here


如果你有NumPy,你可以使用Image.fromarray

import Image
import numpy as np

value = "0110100001100101011011000110110001101111"

carr = np.array([(255,255,255), (0,0,0)], dtype='uint8')
data = carr[np.array(map(int, list(value)))].reshape(-1, 8, 3)
img = Image.fromarray(data, 'RGB')
img.save('/tmp/out.png', 'PNG')

但是这个timeit测试建议使用putdata更快:

value = "0110100001100101011011000110110001101111"*10**5

def using_fromarray():
    carr = np.array([(255,255,255), (0,0,0)], dtype='uint8')
    data = carr[np.array(map(int, list(value)))].reshape(-1, 8, 3)
    img = Image.fromarray(data, 'RGB')
    return img

def using_putdata():
    cmap = {'0': (255,255,255),
            '1': (0,0,0)}

    data = [cmap[letter] for letter in value]
    img = Image.new('RGB', (8, len(value)//8), "white")
    img.putdata(data)
    return img

In [79]: %timeit using_fromarray()
1 loops, best of 3: 1.67 s per loop

In [80]: %timeit using_putdata()
1 loops, best of 3: 632 ms per loop

答案 1 :(得分:1)

对于1bit /像素的图像:

im = Image.new('1', (image_width, image_height), "black")

cmap = {'0': 0,
        '1': 1}

data = [cmap[letter] for letter in data_bin]
im.putdata(data)