问题描述
我正在尝试将 PIL 图像的 numpy 数组转换为二进制数组,但我尝试过的任何方法都不起作用。 这是我目前得到的:
from PIL import Image
import numpy as np
pixels=np.array(Image.open("covid_encrypted_new.png").getdata())
def to_bin(pixels):
return [format(i,"08b") for i in pixels]
此外,当我尝试遍历数组并将每个值更改为类型 bin 时,它对我来说也不太顺利。 我还能尝试什么? 谢谢
解决方法
这可能是你想要的
或者在这里:How to read the file and convert it to a binary image in Python
# Read Image
img= Image.open(file_path)
# Convert Image to Numpy as array
img = np.array(img)
# Put threshold to make it binary
binarr = np.where(img>128,255,0)
# Covert numpy array back to image
binimg = Image.fromarray(binarr)
你甚至可以使用 opencv 进行转换
img = np.array(Image.open(file_path))
_,bin_img = cv2. threshold(img,127,cv2.THRESH_BINARY)