Write pfm file. Args: path (str): pathto file image (array): data scale (int, optional): Scale. Defaults to 1.
(path, image, scale=1)
| 56 | |
| 57 | |
| 58 | def write_pfm(path, image, scale=1): |
| 59 | """Write pfm file. |
| 60 | |
| 61 | Args: |
| 62 | path (str): pathto file |
| 63 | image (array): data |
| 64 | scale (int, optional): Scale. Defaults to 1. |
| 65 | """ |
| 66 | |
| 67 | with open(path, "wb") as file: |
| 68 | color = None |
| 69 | |
| 70 | if image.dtype.name != "float32": |
| 71 | raise Exception("Image dtype must be float32.") |
| 72 | |
| 73 | image = np.flipud(image) |
| 74 | |
| 75 | if len(image.shape) == 3 and image.shape[2] == 3: # color image |
| 76 | color = True |
| 77 | elif ( |
| 78 | len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1 |
| 79 | ): # greyscale |
| 80 | color = False |
| 81 | else: |
| 82 | raise Exception("Image must have H x W x 3, H x W x 1 or H x W dimensions.") |
| 83 | |
| 84 | file.write("PF\n" if color else "Pf\n".encode()) |
| 85 | file.write("%d %d\n".encode() % (image.shape[1], image.shape[0])) |
| 86 | |
| 87 | endian = image.dtype.byteorder |
| 88 | |
| 89 | if endian == "<" or endian == "=" and sys.byteorder == "little": |
| 90 | scale = -scale |
| 91 | |
| 92 | file.write("%f\n".encode() % scale) |
| 93 | |
| 94 | image.tofile(file) |
| 95 | |
| 96 | |
| 97 | def read_image(path): |