读取图像文件

Den*_*nis 5 python windows binary type-conversion

我有这张白色和黑色方块的图片。每个方块代表 0-黑色和 1-白色。有没有办法从左到右扫描图像并将二进制输出写入 .txt 文件?我需要用 python 来做。谢谢 这是图片

小智 1

尝试这样的事情:

from PIL import Image
import numpy as np

def image_to_txt(image_path, output_file):
    # Open the image
    image = Image.open(image_path)
    
    # Convert the image to grayscale
    image = image.convert("L")
    
    # Convert the image to a NumPy array
    image_array = np.array(image)
    
    # Write the NumPy array to a text file
    with open(output_file, "w") as file:
        np.savetxt(file, image_array, fmt='%d')

# Replace 'input_image.png' with your image file and 'output.txt' with the desired output file name
image_to_txt('input_image.png', 'output.txt')
Run Code Online (Sandbox Code Playgroud)