Read a normal image, return float32 normal array of shape (H, W, 3).
(path: Union[str, os.PathLike, IO])
| 200 | |
| 201 | |
| 202 | def read_normal(path: Union[str, os.PathLike, IO]) -> np.ndarray: |
| 203 | """ |
| 204 | Read a normal image, return float32 normal array of shape (H, W, 3). |
| 205 | """ |
| 206 | if isinstance(path, (str, os.PathLike)): |
| 207 | data = Path(path).read_bytes() |
| 208 | else: |
| 209 | data = path.read() |
| 210 | normal = cv2.cvtColor(cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB) |
| 211 | mask_nan = np.all(normal == 0, axis=-1) |
| 212 | normal = (normal.astype(np.float32) / 65535 - 0.5) * [2.0, -2.0, -2.0] |
| 213 | normal = normal / (np.sqrt(np.square(normal[..., 0]) + np.square(normal[..., 1]) + np.square(normal[..., 2])) + 1e-12) |
| 214 | normal[mask_nan] = np.nan |
| 215 | return normal |
| 216 | |
| 217 | |
| 218 | def write_normal(path: Union[str, os.PathLike, IO], normal: np.ndarray, compression_level: int = 7) -> np.ndarray: |