Read pfm file. Args: path (str): path to file Returns: tuple: (data, scale)
(path)
| 7 | |
| 8 | |
| 9 | def read_pfm(path): |
| 10 | """Read pfm file. |
| 11 | |
| 12 | Args: |
| 13 | path (str): path to file |
| 14 | |
| 15 | Returns: |
| 16 | tuple: (data, scale) |
| 17 | """ |
| 18 | with open(path, "rb") as file: |
| 19 | |
| 20 | color = None |
| 21 | width = None |
| 22 | height = None |
| 23 | scale = None |
| 24 | endian = None |
| 25 | |
| 26 | header = file.readline().rstrip() |
| 27 | if header.decode("ascii") == "PF": |
| 28 | color = True |
| 29 | elif header.decode("ascii") == "Pf": |
| 30 | color = False |
| 31 | else: |
| 32 | raise Exception("Not a PFM file: " + path) |
| 33 | |
| 34 | dim_match = re.match(r"^(\d+)\s(\d+)\s$", file.readline().decode("ascii")) |
| 35 | if dim_match: |
| 36 | width, height = list(map(int, dim_match.groups())) |
| 37 | else: |
| 38 | raise Exception("Malformed PFM header.") |
| 39 | |
| 40 | scale = float(file.readline().decode("ascii").rstrip()) |
| 41 | if scale < 0: |
| 42 | # little-endian |
| 43 | endian = "<" |
| 44 | scale = -scale |
| 45 | else: |
| 46 | # big-endian |
| 47 | endian = ">" |
| 48 | |
| 49 | data = np.fromfile(file, endian + "f") |
| 50 | shape = (height, width, 3) if color else (height, width) |
| 51 | |
| 52 | data = np.reshape(data, shape) |
| 53 | data = np.flipud(data) |
| 54 | |
| 55 | return data, scale |
| 56 | |
| 57 | |
| 58 | def write_pfm(path, image, scale=1): |