在python中读取PFM格式

时间:2018-02-15 14:19:23

标签: python image-processing

我想在python中阅读pfm格式的图像。我尝试使用imageio.read,但它抛出了一个错误。我可以提出任何建议吗?

img = imageio.imread('image.pfm')

2 个答案:

答案 0 :(得分:1)

我对Python并不熟悉,但这里有一些关于阅读PFM Portable Float Map )文件的建议。

选项1

ImageIO 文档here表明您可以下载并使用 FreeImage 阅读器。

选项2

我在下面拼凑了一个简单的读者,这似乎可以在我在'net周围找到并使用 ImageMagick 生成的一些示例图像上正常工作。它可能包含效率低下或不良做法,因为我不会说Python。

#!/usr/local/bin/python3
import sys
import re
from struct import *

# Enable/disable debug output
debug = True

with open("image.pfm","rb") as f:
    # Line 1: PF=>RGB (3 channels), Pf=>Greyscale (1 channel)
    type=f.readline().decode('latin-1')
    if "PF" in type:
        channels=3
    elif "Pf" in type:
        channels=1
    else:
        print("ERROR: Not a valid PFM file",file=sys.stderr)
        sys.exit(1)
    if(debug):
        print("DEBUG: channels={0}".format(channels))

    # Line 2: width height
    line=f.readline().decode('latin-1')
    width,height=re.findall('\d+',line)
    width=int(width)
    height=int(height)
    if(debug):
        print("DEBUG: width={0}, height={1}".format(width,height))

    # Line 3: +ve number means big endian, negative means little endian
    line=f.readline().decode('latin-1')
    BigEndian=True
    if "-" in line:
        BigEndian=False
    if(debug):
        print("DEBUG: BigEndian={0}".format(BigEndian))

    # Slurp all binary data
    samples = width*height*channels;
    buffer  = f.read(samples*4)

    # Unpack floats with appropriate endianness
    if BigEndian:
        fmt=">"
    else:
        fmt="<"
    fmt= fmt + str(samples) + "f"
    img = unpack(fmt,buffer)

选项3

如果您无法在Python中阅读PFM文件,可以使用 ImageMagick 在命令行将它们转换为可以存储浮点样本的其他格式,例如TIFF。 ImageMagick 安装在大多数Linux发行版上,可用于macOS和Windows:

magick input.pfm output.tif

答案 1 :(得分:0)

img = imageio.imread('image.pfm')

会做到这一点。为了易于使用,可以将其转换为numpy数组。

img = numpy.asarray(img)