读取图像文件

问题描述 投票:0回答:1

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

python windows binary type-conversion
1个回答
0
投票

尝试这样的事情:

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')
© www.soinside.com 2019 - 2024. All rights reserved.