读取图像文件

3
我有一张由白色和黑色方块组成的图片。每个方块代表一个二进制数,0代表黑色,1代表白色。有没有办法从左到右扫描这张图片,并将二进制输出写入一个.txt文件?我需要用Python来实现这个功能。 谢谢。 这是图片的链接

使用图像处理库来将图像转换为2D数组(像素数组),并使用该数组根据像素值构建二进制字符串。Pillow应该能够毫无问题地完成这个任务。 - undefined
提供的图像尺寸为1920x1080像素。您需要1920x1080的矩阵还是QR码的实际矩阵尺寸? - undefined
文本文件会是什么样子?每个图像行占据一行?数值之间用逗号分隔? - undefined
@MarkSetchell 只有一行长的内容 - undefined
2个回答

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')

直接从ChatGPT出来的吗? - undefined

0
这样的话应该能满足你的需求。
#!/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()]

在这张图片链接中,前10个方块是白色的,接下来一个是黑色的,然后两个白色的,三个黑色的,以此类推。在输出中,我看到数字是按照正确的顺序排列的,但是我得到的数字比方块的数量多。这是前16个方块的数字(000000000000011111000001111111111),而在这种情况下,我需要的是(0000000000100111)。希望你能理解我的回答,因为英语不是我的母语。 - undefined
图片的尺寸是1920x1080,我的脚本生成了准确的2,073,600(1920*1080)个数字。前50个是白色的,接下来的5个是黑色的,所以看起来你正在使用一个尺寸缩小了5倍的图片,原因不明。请检查你的图片尺寸。 - undefined
我觉得可能有误解。当你说“前50个是白色的…”时,你是指像素吗?因为我不是在寻找像素的数量,而是正方形的数量。接下来的5个黑色像素形成一个正方形(5x5)。 - undefined
我在代码中添加了一行额外的代码,将图像在每个方向上缩小了5倍,这样像素现在对应于块。 - undefined
你对这个答案怎么样? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接