google-research
70 строк · 1.8 Кб
1# coding=utf-8
2# Copyright 2024 The Google Research Authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""utility function to read midas outputs."""
17# from midas/utils.py
18import re
19import numpy as np
20
21
22def read_pfm(path):
23"""Read pfm file.
24
25Args:
26path (str): path to file
27
28Returns:
29tuple: (data, scale)
30
31Raises:
32Exception: for invalid pfm file
33"""
34with open(path, "rb") as file:
35color = None
36width = None
37height = None
38scale = None
39endian = None
40
41header = file.readline().rstrip()
42if header.decode("ascii") == "PF":
43color = True
44elif header.decode("ascii") == "Pf":
45color = False
46else:
47raise Exception("Not a PFM file: " + path)
48
49dim_match = re.match(r"^(\d+)\s(\d+)\s$", file.readline().decode("ascii"))
50if dim_match:
51width, height = list(map(int, dim_match.groups()))
52else:
53raise Exception("Malformed PFM header.")
54
55scale = float(file.readline().decode("ascii").rstrip())
56if scale < 0:
57# little-endian
58endian = "<"
59scale = -scale
60else:
61# big-endian
62endian = ">"
63
64data = np.fromfile(file, endian + "f")
65shape = (height, width, 3) if color else (height, width)
66
67data = np.reshape(data, shape)
68data = np.flipud(data)
69
70return data, scale
71