阅读python中的PFM格式

2024-05-15 11:07:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想阅读python中pfm格式的图像。我试过了图像读取但这是一个错误。我能有什么建议吗?在

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


Tags: 图像imageimg格式错误建议imreadimageio
1条回答
网友
1楼 · 发布于 2024-05-15 11:07:59

我对Python一点都不熟悉,但是这里有一些关于阅读PFM可移植Float Map)文件的建议。在


选项1

ImageIO文档here表明有一个免费图像阅读器可以下载和使用。在


选项2

我自己在下面拼凑了一个简单的阅读器,它似乎能很好地处理我在网上找到的几个用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:

^{pr2}$

相关问题 更多 >