使用 PIL 将 PNG 图像转换为 PBM(仅 1 和 0)

发布于 2025-01-09 15:51:46 字数 512 浏览 0 评论 0原文

我正在尝试将 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,以便我能够操纵它?

I am trying to convert PNG images to PBM files. These PNG files are black and white and I need the resulting PBM to be a P1 bitmap which only contains 1s and 0s. So far the closest I have come is the following code:

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

However, this does not result in the desired output. When I open the output file in VS code, I get a bunch of question marks in diamond boxes along with red null boxes (it will not allow me to attach images here). When I open the file in notepad, it is blank spaces and y's with double dots above them. Does anyone know why my output is not 1s and 0s with the number of rows and columns corresponding to the size of the PNG I am converting?

Edit: I saw the post saying that I shouldn't expect to see the ASCII digits of 1s and 0s but that when I open it in a PBM viewer I would see the image I started with. This is correct, but unfortunately, I need the ASCII digits for the project I am working on. Does anyone know how I can do the conversion such that I end up with straight 1s and 0s so that I am able to manipulate it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

恬淡成诗 2025-01-16 15:51:46

PIL 不支持 PBM 的 ASCII 格式,但在它的帮助下自己做起来相当容易,因为 PBM 文件格式 就是这么简单。下面的代码基于我对问题如何将灰度图像转换为像素值列表?

注意,如果您想要的只是 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')

此测试图像:

test image

生成了包含以下内容的 PBM 格式文件:

输出

PIL doesn't support ASCII format of PBM, but it's fairly easy to do yourself with its help because the PBM file format is so simple. The code below is based on my answer to the question How to convert a grayscale image into a list of pixel values?

Note that if all you want are the ASCII digits, that's what ends up in the data list which is written to the output file.

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

This test image:

test image

Produced a PBM format file with this content:

output

送君千里 2025-01-16 15:51:46

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

Numpy can save your array quite simply for you via np.savetxt() as follows:

#!/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')

If you want the full PBM header, replace the last line above with the following three lines:

# 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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文