Hsyshasuzh's picture
download
raw
1.42 kB
from pathlib import Path
import numpy as np
from PIL import Image
def load_rgb(source):
if isinstance(source, (str, Path)):
path = Path(source)
if path.suffix.lower() in {'.tif', '.tiff'}:
import rasterio
with rasterio.open(path) as raster:
if raster.count < 3 or any(dtype != 'uint8' for dtype in raster.dtypes[:3]):
raise ValueError('TIFF input must contain three uint8 RGB bands')
pixels = np.moveaxis(raster.read((1, 2, 3)), 0, -1)
valid = raster.dataset_mask() > 0
else:
with Image.open(path) as image:
if image.mode not in ('RGB', 'RGBA'):
raise ValueError('input must be an RGB/RGBA image')
valid = np.asarray(image.getchannel('A')) > 0 if image.mode == 'RGBA' else np.ones((image.height,image.width),bool)
pixels = np.asarray(image.convert('RGB'))
elif isinstance(source, np.ndarray):
pixels = source
valid = np.ones(pixels.shape[:2], bool)
else:
raise ValueError('source must be a path or HWC uint8 RGB array')
if pixels.dtype != np.uint8 or pixels.ndim != 3 or pixels.shape[2] != 3 or min(pixels.shape[:2]) == 0:
raise ValueError('nonempty HWC uint8 RGB image required')
valid &= ~np.all(pixels == 0, axis=-1)
return np.ascontiguousarray(pixels), valid

Xet Storage Details

Size:
1.42 kB
·
Xet hash:
168a742a3670f4b9e46cd8e744982bca934878e6577267b16463fb1310508cb5

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.