| 1 |
import os |
| 2 |
import os.path as osp |
| 3 |
import pathlib |
| 4 |
from typing import Union |
| 5 |
|
| 6 |
import numpy as np |
| 7 |
import PIL.Image |
| 8 |
|
| 9 |
from .. import utils |
| 10 |
from ..label import label_colormap |
| 11 |
|
| 12 |
|
| 13 |
def imread(filename): |
| 14 |
|
| 15 |
"""Read image from file. |
| 16 |
|
| 17 |
Parameters |
| 18 |
---------- |
| 19 |
filename: str |
| 20 |
Filename. |
| 21 |
|
| 22 |
Returns |
| 23 |
------- |
| 24 |
img: numpy.ndarray, (H, W) or (H, W, 3) or (H, W, 4) |
| 25 |
Image read. |
| 26 |
""" |
| 27 |
return utils.pillow_to_numpy(PIL.Image.open(filename)) |
| 28 |
|
| 29 |
|
| 30 |
def imsave(filename, arr): |
| 31 |
|
| 32 |
"""Save image to file. |
| 33 |
|
| 34 |
Parameters |
| 35 |
---------- |
| 36 |
filename: str |
| 37 |
Filename. |
| 38 |
arr: numpy.ndarray, (H, W) or (H, W, 3) or (H, W, 4) |
| 39 |
Image to save. |
| 40 |
|
| 41 |
Returns |
| 42 |
------- |
| 43 |
None |
| 44 |
|
| 45 |
""" |
| 46 |
try: |
| 47 |
os.makedirs(osp.dirname(filename)) |
| 48 |
except OSError: |
| 49 |
pass |
| 50 |
return utils.numpy_to_pillow(arr).save(filename) |
| 51 |
|
| 52 |
|
| 53 |
def lblsave(filename: Union[str, pathlib.Path], lbl: np.ndarray) -> None: |
| 54 |
"""Save label image to PNG file with a colormap. |
| 55 |
|
| 56 |
Parameters |
| 57 |
---------- |
| 58 |
filename: str | pathlib.Path |
| 59 |
Filename. Must end with '.png'. |
| 60 |
lbl: numpy.ndarray, (H, W), np.uint8 |
| 61 |
Label image to save. |
| 62 |
|
| 63 |
Returns |
| 64 |
------- |
| 65 |
None |
| 66 |
|
| 67 |
""" |
| 68 |
if not str(filename).lower().endswith(".png"): |
| 69 |
raise ValueError(f"filename must end with '.png': {filename}") |
| 70 |
if lbl.dtype != np.uint8: |
| 71 |
raise ValueError(f"lbl.dtype must be np.uint8, but got {lbl.dtype}") |
| 72 |
|
| 73 |
lbl_pil = PIL.Image.fromarray(lbl, mode="P") |
| 74 |
colormap = label_colormap(n_label=256) |
| 75 |
lbl_pil.putpalette(colormap.flatten()) |
| 76 |
lbl_pil.save(filename) |