我正在尝试从图像(如\ xff
)中提取二进制信息,并将其保存到文本文件中。最终,我还应该能够反转效果,并从文本文件生成图像。
我使用下面的代码来尝试创建文本文件;它不会抛出错误,但生成的文本不会生成图像。Here is an example of the contents of one of the text files created by this code.
file = open(image, "rb")
data = file.read()
file.close()
file = open(txt file, "w")
file.write(str(data))
file.close()
发布于 2021-01-01 11:57:10
你应该用open()函数上的"rb“和"wb”属性在二进制模式下读/写你的文件:
试试这个:
with open(image1, "rb") as input_file:
data = input_file.read()
with open(image2, "wb") as output_file:
output_file.write(data)
但是,如果您想要将目标文件字节转换为位(01)并保存它们,然后再次反转此作业,您可以简单地使用numpy包:
试试这个:
import numpy as np
Bytes = np.fromfile("image1.png", dtype="uint8")
Bits = np.unpackbits(Bytes)
with open("bits.txt", "w") as export_bits:
export_bits.write("".join(list(map(str, Bits))))
with open("bits.txt", "r") as load_bits:
string_bits_data = list(map(int, load_bits.read()))
save_new_image = np.packbits(string_bits_data).astype('int8').tofile("image2.png")
print("Done")
致谢给米哈伊尔-v (UID: 4157407)来自:Convert bytes to bits in python。
https://stackoverflow.com/questions/65525565
复制相似问题