你的文件是P2
type PGM,这意味着它是 ASCII 格式 - 您可以在普通文本编辑器中查看它。看来两者都不是PIL, nor skimage想要阅读该内容,但很高兴阅读相应的内容P5
type 是相同的,只是它是用二进制而不是 ASCII 编写的。
有几个选项...
1)你可以使用OpenCV阅读它:
import cv2
im = cv2.imread('a.pgm')
2)你可以将其转换为P5
with 图像魔术师然后阅读output.pgm
文件与skimage or PIL:
magick input.pgm output.pgm
3)如果添加OpenCV, or 图像魔术师因为依赖对你来说是一种真正的痛苦,所以它是possible自己读取 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))