PFM is a file format that uses floating-point numbers to store pictures, including file information header and binary data raster. In some data sets, disparity maps stored in pfm format can often be seen. Files in pfm format are not conducive to browsing, and can be converted into png format files for easy browsing.
The PFM header file has 3 lines:
Binary data area:
The order of reading the images is from bottom to top and from left to right.
When the pfm file has only one picture matrix, the code is as follows:
# -*- 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()
Reference blog:
https://blog.csdn.net/weixin_44899143/article/details/89186891 PFM format image and read middlebury data set
https://blog.csdn.net/qq_43225437/article/details/86589892 python: npy format to png format (source code)