使用 PIL 将 PNG 图像转换为 PBM(仅 1 和 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PIL 不支持 PBM 的 ASCII 格式,但在它的帮助下自己做起来相当容易,因为 PBM 文件格式 就是这么简单。下面的代码基于我对问题如何将灰度图像转换为像素值列表?
注意,如果您想要的只是 ASCII 数字,那么这就是写入输出文件的
data
列表中的内容。此测试图像:
生成了包含以下内容的 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.This test image:
Produced a PBM format file with this content:
Numpy 可以通过
np.savetxt()
非常简单地为您保存数组,如下所示:如果您想要完整的 PBM 标头,请将上面的最后一行替换为以下三行:
Numpy can save your array quite simply for you via
np.savetxt()
as follows:If you want the full PBM header, replace the last line above with the following three lines: