Python 将单色图像转换为二进制字符串的最佳方法是什么?

Python 将单色图像转换为二进制字符串的最佳方法是什么?,python,python-3.x,image,encryption,binary,Python,Python 3.x,Image,Encryption,Binary,目前我的计划是使用numpy.ndarray.tolist(numpy.asarray(img))并迭代每三个元素(因为每个像素都表示为三个RGB整数),检查它是否为零以生成二进制字符串。我确信一定有更好的方法来做到这一点,我只是不确定是什么…Numpy和Pillow是非常好的朋友。只需将图像作为参数提供,即可将枕头图像转换为numpy数组: from PIL import Image import numpy as np path = "path\to\image.jpg&

目前我的计划是使用
numpy.ndarray.tolist(numpy.asarray(img))
并迭代每三个元素(因为每个像素都表示为三个RGB整数),检查它是否为零以生成二进制字符串。我确信一定有更好的方法来做到这一点,我只是不确定是什么…

Numpy和Pillow是非常好的朋友。只需将图像作为参数提供,即可将枕头图像转换为numpy数组:

 from PIL import Image 
 import numpy as np

 path = "path\to\image.jpg"
 image_file = Image.open(path) 
 bilevel_img = image_file.convert('1')
 data_array = np.array(bilevel_img)
 print(data_array)
请注意,“1”模式是两层模式,因此您将得到一个真/假数组

使用灰度模式,然后按照您定义的阈值进行二层化,可能会更好:

 gray = np.array(img.convert("L"))
 print(gray)
 threshold = 128 # cutoff between 0 and 255
 bilevel_array = (gray > threshold).astype(int)
 print(bilevel_array)

这将为您提供一个二进制数组

谢谢你的帮助,虽然我确实需要一个不同的解决方案,但我还是从你的回答中学到了一些东西!