问题描述
所以,我想要做的是有PIL创建基于二进制串的图像。
一些背景故事:
So, what I'm trying to do is have PIL create an image based on a string of binary.Some backstory:
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
^这将返回各对应位颜色元组,如果我称之为:
^This returns a color tuple for each corresponding bit, and if I call:
for i in vdiv:
for i2 in i:
print diff(i2)
这将打印各种颜色元组中列出的每个字节位。 (0,0,0)(0,0,0)(255,255,255)...
我想知道的是,我怎样才能得到PIL要创造一个像素的二进制字符串匹配的图像?
What I want to know is, How can I get PIL to create an image where the pixels match the binary string?
这里是它应该是什么样子:
Here is what it should look like.:
我迄今为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()
这是在范围X
这让我一下。我迷路了。
It is the for x in range
bit that gets me. I am lost.
推荐答案
您可以使用 img.putdata code>:
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()
如果您有numpy的,你也可以使用 Image.fromarray
:
If you have NumPy, you could instead use 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 code>更快:
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
这篇关于谈到二进制字符串与PIL图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!