我有一张由白色和黑色方块组成的图片。每个方块代表一个二进制数,0代表黑色,1代表白色。有没有办法从左到右扫描这张图片,并将二进制输出写入一个.txt文件?我需要用Python来实现这个功能。
谢谢。
这是图片的链接
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')
#!/usr/bin/env python3
import sys
from PIL import Image, ImageOps
# Open image and ensure in mode "1"
filename = sys.argv[1]
im = Image.open(filename).convert('1')
# Scale down by a factor of 5 so one block = 1 pixel
im = ImageOps.scale(im, 1/5.0, resample = Image.Resampling.NEAREST)
[ print(f'{int(p/255)}', end='') for p in im.getdata()]