首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用python和PIL模块导入PPM映像

用python和PIL模块导入PPM映像
EN

Stack Overflow用户
提问于 2010-11-04 21:27:32
回答 6查看 29.1K关注 0票数 2

我需要一种方法,我可以读取线和提取像素信息到某种结构,所以我可以使用腐像素功能,以创建一个图像基于ppm p3文件。

我正在使用Python图像库(,PIL),我希望打开一个PPM映像,并将其显示为屏幕上的图像。

我怎么能只用PIL就能做到这一点呢?

这是我的ppm图像。这只是我创建的一个7x1图像。

代码语言:javascript
复制
P3
# size 7x1
7 1
255
0
0
0
201
24
24
24
201
45
24
54
201
201
24
182
24
201
178
104
59
14
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-11-28 21:22:13

编辑:修改问题后的,只允许读行,检查下面的链接。它解释了如何编写加载文件的包装器。我要亲自测试一下它应该能用..。

您当前(11/2010)无法使用PIL打开普通PPM图像。这里平淡的意思是阿西。但是,二进制版本可以工作。造成这种情况的主要原因是ascii文件没有固定的每个像素位数。这就是PIL中的图像加载程序所假设的。我有一个相关的问题:

如何为普通pgm格式编写PIL图像过滤器?

我计划为普通的PPM写一个PIL过滤器,但我的时间很短。如果你有兴趣帮忙,请告诉我。

比尔,

朱哈

票数 2
EN

Stack Overflow用户

发布于 2012-06-22 19:50:43

如果您喜欢使用np.array对象,只需这样做:

代码语言:javascript
复制
>>> from scipy.misc import imread
>>> img = imread(path_to_ppm_file)
>>> img.shape
>>> (234, 555, 3)
票数 6
EN

Stack Overflow用户

发布于 2021-02-03 23:51:16

一些背景概念‍使用您的确切示例:

  • .ppm是存储图像数据的文件格式之一,因此它更具有可读性。
  • 它代表便携式PixMap格式
  • 这些文件通常采用以下格式:
代码语言:javascript
复制
# Optional Comments likes this one
# The first line is the image header which contains the format followed by width and height
P3 7 1
# Second line contains the maximum value possible for each color point
255
# Third line onwards, it contains the pixels represented in rows(7) and columns(1)
0 0 0
201 24 24 
24 201 45 
24 54 201
201 24 182 
24 201 178 
104 59 14

参考文献

因此,您可以看到您已经正确地重写了PPM文件(因为RGB三胞胎被考虑用于彩色图像中的每个像素)。

打开文件并将其可视化

OpenCV (做得很好)

代码语言:javascript
复制
import cv2
import matplotlib.pyplot as plt
img = cv2.imread("\path to the image")
# Remember, opencv by default reads images in BGR rather than RGB
# So we fix that by the following
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
# Now, for small images like yours or any similar ones we use for example purpose to understand image processing operations or computer graphics
# Using opencv's cv2.imshow()
# Or google.colab.patches.cv2_imshow() [in case we are on Google Colab]
# Would not be of much use as the output would be very small to visualize
# Instead using matplotlib.pyplot.imshow() would give a decent visualization
plt.imshow(img)

枕头(或我们称之为PIL)

尽管文档声明我们可以使用以下方法直接打开.ppm文件:

代码语言:javascript
复制
from PIL import Image
img = Image.open("path_to_file")

参考文献

但是,当我们进一步检查时,我们可以看到它们只支持二进制版本(否则称为P6版本),而不支持ASCII版本(否则称为P3版本)。

参考文献

因此,对于您的用例,使用PIL并不是理想的选择❌。

使用matplotlib.pyplot.imshow()可视化的好处应如上所示。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4101576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档