【问题标题】:Error Opening PGM file with PIL and SKIMAGE使用 PIL 和 SKIMAGE 打开 PGM 文件时出错
【发布时间】:2020-06-04 04:16:44
【问题描述】:

我有以下图片文件:

Image

我使用 PIL 和 Skimage 打开它,但出现以下错误

首先使用 PIL(尝试使用和不使用 trucate 选项): 代码:

from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
img = Image.open("image_output.pgm")

错误:

OSError: cannot identify image file 'image_output.pgm'

还有 Skimage:

代码:

from skimage import io
img = io.imread("image_output.pgm")

错误:

OSError: cannot identify image file <_io.BufferedReader name='image_output.pgm'>

我可以使用系统照片查看器和 Matlab 等 GUI 应用程序打开文件。

如何诊断图像有什么问题?我将字节数据与可以在 Python 中打开的其他 PGM 文件进行了比较,但无法识别差异。

谢谢。

【问题讨论】:

  • 您的链接似乎无效 - 请检查一下。
  • 另外,您没有显示打开它的代码。
  • @MarkSetchell 我已经修复了图片链接并添加了代码。请让我知道您是否可以下载图像。另外,如果您投票支持“关闭”,请重新考虑。
  • 关闭投票不是来自我。下面回答:-)

标签: python-3.x python-imaging-library scikit-image pgm


【解决方案1】:

您的文件是P2 类型PGM,这意味着它是ASCII - 您可以在普通文本编辑器中查看它。似乎 PILskimage 都不想阅读它,但很高兴阅读相应的 P5 类型,除了它是用二进制而不是 ASCII 编写的之外,它是相同的.

有几个选项...


1) 你可以使用 OpenCV 来阅读它:

import cv2
im = cv2.imread('a.pgm')

2) 您可以使用 ImageMagick 将其转换为 P5,然后使用 skimagePIL 读取 output.pgm 文件:

magick input.pgm output.pgm

3) 如果添加 OpenCVImageMagick 作为依赖项对您来说真的很痛苦,那么可以读取 PGM 图像你自己:

#!/usr/bin/env python3

import re
import numpy as np

# Open image file, slurp the lot
with open('input.pgm') as f:
   s = f.read()

# Find anything that looks like numbers
# Technically, there could be comments that should be ignored
l=re.findall(r'[0-9P]+',s)

# List "l" will contain: P5, width, height, 255, pixel1, pixel2, pixel3...
# Technically, if l[3]>255, you should change the type of the Numpy array to uint16, but that is not the case
w, h = int(l[1]), int(l[2])

# Make Numpy image from data
ni = np.array(l[4:],dtype=np.uint8).reshape((h,w))

【讨论】:

  • 谢谢!我在研究所的机器上并且没有安装 CV2(我在发布之前尝试过测试,但不能)。此外,我正要安装 Imagemagick,但使用第三个选项,我不必安装。重要的是,感谢您的解释。
  • 看起来像动脉中的超声波探头!
  • 它是来自“Axbench”基准套件的医学成像应用程序“SRAD”的输出图像。所以,我不是专家,但你一定是对的!基准链接:axbench.org
猜你喜欢
  • 2012-09-27
  • 1970-01-01
  • 2021-12-05
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 2015-10-26
  • 1970-01-01
相关资源
最近更新 更多