【问题标题】:Image Conversion from PNG to PBM (solely 1s and 0s) using PIL使用 PIL 将图像从 PNG 转换为 PBM(仅 1 和 0)
【发布时间】:2022-02-24 18:23:17
【问题描述】:

我正在尝试将 PNG 图像转换为 PBM 文件。这些 PNG 文件是黑白的,我需要生成的 PBM 是仅包含 1 和 0 的 P1 位图。到目前为止,我最接近的是以下代码:

img = Image.open("test part stl00000.png")
img = img.convert('1')
img.save("new.pbm")

但是,这不会产生所需的输出。当我在 VS 代码中打开输出文件时,我会在菱形框中看到一堆问号以及红色的空框(它不允许我在此处附加图像)。当我在记事本中打开文件时,它是空格,y 上面有双点。有谁知道为什么我的输出不是 1 和 0,而行数和列数对应于我正在转换的 PNG 的大小?

编辑:我看到帖子说我不应该期望看到 1 和 0 的 ASCII 数字,但是当我在 PBM 查看器中打开它时,我会看到我开始使用的图像.这是正确的,但不幸的是,我需要我正在从事的项目的 ASCII 数字。有谁知道我如何进行转换,以便最终得到直接的 1 和 0,以便我能够操纵它?

【问题讨论】:

  • 菱形框也像其他计算机文件一样由 1 和 0 组成。当您在文本编辑器中打开二进制文件时,您不应期望看到字面上的 ASCII 数字 0 (ASCII 48) 和 1 (ASCII 49)。为什么不在 PBM 查看器而不是记事本中打开它们?
  • 我不知道您是否只是想完成工作以实际做其他事情,或者您是否想具体了解如何使用 Python 和 PIL 进行转换。如果是前者,仅供参考,您可以在没有任何 Python 的情况下执行此操作,只需在终端中使用 ImageMagick 使用 magick input.png -compresss none output.pbm。

标签: python python-imaging-library png image-conversion pbm


【解决方案1】:

PIL 不支持 PBM 的 ASCII 格式,但是在它的帮助下自己做起来相当容易,因为 PBM file format 非常简单。下面的代码是基于my answer到问题How to convert a grayscale image into a list of pixel values?

注意,如果您想要的只是 ASCII 数字,那么这就是写入输出文件的 data 列表中的内容。

from pathlib import Path
from PIL import Image

ASCII_BITS = '0', '1'
imagepath = Path('peace_sign.png')

img = Image.open(imagepath).convert('1')  # Convert image to bitmap.
width, height = img.size

# Convert image data to a list of ASCII bits.
data = [ASCII_BITS[bool(val)] for val in img.getdata()]
# Convert that to 2D list (list of character lists)
data = [data[offset: offset+width] for offset in range(0, width*height, width)]

with open(f'{imagepath.stem}.pbm', 'w') as file:
    file.write('P1\n')
    file.write(f'# Conversion of {imagepath} to PBM format\n')
    file.write(f'{width} {height}\n')
    for row in data:
        file.write(' '.join(row) + '\n')

print('fini')

这个测试图片:

制作了一个包含此内容的 PBM 格式文件:

【讨论】:

    【解决方案2】:

    Numpy 可以通过np.savetxt() 为您非常简单地保存您的数组,如下所示:

    #!/usr/bin/env python3
    
    import numpy as np
    from PIL import Image
    
    # Load image and convert to '1' mode
    im = Image.open('image.png').convert('1')
    
    # Make Numpy array from image
    na = np.array(im)
    
    # Save array
    np.savetxt('image.pbm', na, fmt='%d')
    

    如果您想要完整的 PBM 标头,请将上面的最后一行替换为以下三行:

    # Use this to put NetPBM header on as well
    # https://en.wikipedia.org/wiki/Netpbm#PBM_example
    
    with open('image.pbm','w') as f:
        f.write(f'P1\n{im.width} {im.height}\n')
        np.savetxt(f, na, fmt='%d')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-15
      • 2016-05-29
      • 2019-02-17
      • 2012-02-28
      • 1970-01-01
      • 2014-11-02
      • 2015-12-31
      • 1970-01-01
      相关资源
      最近更新 更多