提问人:Denis 提问时间:11/18/2023 最后编辑:Denis 更新时间:11/22/2023 访问量:99
读取图像文件
Read image file
问:
我有这张白色和黑色方块的照片。每个方块代表 0-黑色和 1-白色。有没有办法从左到右扫描图像并将二进制输出写入 .txt 文件?我需要用python来做。 谢谢 这是图片
答:
1赞
Leo
11/18/2023
#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')
评论
0赞
SKPS
11/18/2023
直接从chatgpt中出来?
0赞
Mark Setchell
11/20/2023
#2
像这样的东西应该做你想做的事:
#!/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()]
评论
0赞
Denis
11/20/2023
在图像链接中,前 10 个方块是白色的,下一个是黑色的,然后是两个白色的,三个黑色的,依此类推。在输出中,我看到数字的顺序正确,但我得到的数字多于平方数。这是前 16 个方格 (000000000000011111000001111111111) 的数字,在这种情况下,我需要 (0000000000100111)。我希望你能理解这个回复,因为英语不是我的母语
0赞
Mark Setchell
11/21/2023
图像是 1920x1080,我的脚本正好生成 2,073,600 (1920*1080) 位。前 50 个是白色的,接下来的 5 个是黑色的,因此看起来您正在使用的图像由于某种原因将离子大小缩小了 5 倍。请检查图像的尺寸。
0赞
Denis
11/22/2023
我认为有一个误会。“前 50 个是白色的......” - 你是说像素吗?因为我不是在寻找像素数,而是在寻找正方形数。接下来的 5 个黑色像素形成一个正方形 (5x5)
0赞
Mark Setchell
11/22/2023
我添加了一条额外的线,将图像在每个方向上缩小 5 倍,因此像素现在对应于块。
0赞
Mark Setchell
11/27/2023
你是怎么回答这个问题的?
评论