在python中读取PFM格式 [英] Read PFM format in python
问题描述
我想在python中读取pfm格式的图像.我尝试使用imageio.read,但它抛出错误.请问我有什么建议吗?
I want to read pfm format images in python. I tried with imageio.read but it is throwing an error. Can I have any suggestion, please?
img = imageio.imread('image.pfm')
推荐答案
我对Python一点都不熟悉,但是这里有一些阅读PFM
( Portable Float Map )的建议.文件.
I am not at all familiar with Python, but here are a few suggestions on reading a PFM
(Portable Float Map) file.
选项1
ImageIO 文档此处表示您可以下载和使用 FreeImage 阅读器.
The ImageIO documentation here suggests there is a FreeImage reader you can download and use.
选项2
我自己在下面组装了一个简单的阅读器,该阅读器似乎可以很好地处理我在网上找到的,由 ImageMagick 生成的一些示例图像.因为我不会使用Python,所以可能包含效率低下或错误的做法.
I pieced together a simple reader myself below that seems to work fine on a few sample images I found around the 'net and generated with ImageMagick. It may contain inefficiencies or bad practices because I do not speak 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:
If you cannot read your PFM
files in Python, you could convert them at the command line using ImageMagick to another format, such as TIFF, that can store floating point samples. ImageMagick is installed on most Linux distros and is available for macOS and Windows:
magick input.pfm output.tif
这篇关于在python中读取PFM格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!