有了PIL,我如何用位表示b/w图像中的字符串?

2024-09-30 06:30:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试验PIL,具体地说,是从字符串生成图像

我有以下代码:

from __future__ import unicode_literals

import array
from PIL import Image

photo_data = "35c1f6ebc3ef2d424ced351b65be8c396f8396d69411d7e7185f2a5e9eaab7da"

scale = 16  ## equals to hexadecimal
num_of_bits = 8
allbits = []
for i in range(len(photo_data)):
    photobits = bin(int(photo_data[i], scale))[2:].zfill(num_of_bits)
    allbits.append(photobits)

photo_image = Image.frombytes("1", (8, 64), "".join(allbits).replace("1","F"), "raw")

photo_image.show()

这段代码中没有错误,但我看到的图像对我来说并不正确

enter image description here

我希望顶行是“00000011”,但它是“11001111”

它可能与frombytes函数的参数有关。但是什么D

实际上,我要做的是将photo_data字符串中的每个字符表示为图像中的一行,每个启用的位都是黑色的

也许我走错了方向,有更简单的方法吗


Tags: of字符串代码from图像imageimportdata
1条回答
网友
1楼 · 发布于 2024-09-30 06:30:33

您现在拥有的是一系列行,它们表示ASCII字符“0”和“F”的二进制可视化,因为这就是您的列表所包含的内容。”0”表示00110000,“F”表示01000110。这些与您的行匹配,白色为1位,黑色为0位

现在,您正试图用一个字节大小的字符来表示每个像素。但是frombytes实际上期望每比特一个像素,这意味着一个字符代表八个像素。因此,您应该使用序号值等于照片数据字符串值的字符填充数组。因此,例如“d”不应翻译为“13”或“00001101”,而应翻译为第十三个ASCII字符“\r”。通过将转换为int,然后使用chr将其转换回string,可以相当轻松地执行此转换

import struct
from PIL import Image

s = "35c1f6ebc3ef2d424ced351b65be8c396f8396d69411d7e7185f2a5e9eaab7da"
bits = [chr(int(c,16)) for c in s]
photo_image = Image.frombytes("1", (8, 64), "".join(bits), "raw")
photo_image.show()

结果:

enter image description here

如果您希望白色和黑色对应于1和0,而不是相反,则可以通过将整数值与b11111111进行异或来反转整数值

bits = [chr(0xFF ^ int(c,16)) for c in s]

结果:

enter image description here

相关问题 更多 >

    热门问题