PFM是一种用浮点数存储图片的文件格式,包含文件信息header和二进制数据raster。在一些数据集中经常可以看到以pfm格式存储的视差图。pfm格式的文件不利于浏览,可以转成png格式文件已方便浏览。
PFM的头文件共有3行:
二进制数据区:
图像的读取顺序按照从下到上,从左到右进行的顺序进行读取。
当pfm文件只有一张图片的矩阵时,代码如下:
# -*- coding: UTF-8 -*-
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import os
import re
import cv2
def pfm_png_file_name(pfm_file_path,png_file_path):
png_file_path={}
for root,dirs,files in os.walk(pfm_file_path):
for file in files:
file = os.path.splitext(file)[0] + ".png"
files = os.path.splitext(file)[0] + ".pfm"
png_file_path = os.path.join(root,file)
pfm_file_path = os.path.join(root,files)
pfm_png(pfm_file_path,png_file_path)
def pfm_png(pfm_file_path,png_file_path):
with open(pfm_file_path, 'rb') as pfm_file:
header = pfm_file.readline().decode().rstrip()
channel = 3 if header == 'PF' else 1
dim_match = re.match(r'^(\d+)\s(\d+)\s$', pfm_file.readline().decode('utf-8'))
if dim_match:
width, height = map(int, dim_match.groups())
else:
raise Exception("Malformed PFM header.")
scale = float(pfm_file.readline().decode().strip())
if scale < 0:
endian = '<' #little endlian
scale = -scale
else:
endian = '>' #big endlian
disparity = np.fromfile(pfm_file, endian + 'f')
img = np.reshape(disparity, newshape=(height, width))
img = np.flipud(img)
plt.imsave(os.path.join(png_file_path), img)
def main():
pfm_file_dir = '/home/cc/下载/PSMNet-master/dataset/data_scene_flow/training/disp_occ_0'
png_file_dir = '/home/cc/下载/PSMNet-master/dataset/data_scene_flow/training/disp_occ_1'
pfm_png_file_name(pfm_file_dir, png_file_dir)
if __name__ == '__main__':
main()
参考博客:
https://blog.csdn.net/weixin_44899143/article/details/89186891 PFM格式图像和读取middlebury 数据集
https://blog.csdn.net/qq_43225437/article/details/86589892 python : npy格式转png格式(源码)