Spaces:
Paused
Paused
File size: 2,324 Bytes
1fe7075 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | """Image loading and normalisation helpers."""
import io
import cv2
import numpy as np
from PIL import Image, ImageOps
from config.runtime import ROOM_UPLOAD_JPEG_QUALITY, ROOM_UPLOAD_MAX_DIMENSION
from errors import bad_request
def load_tile_image(contents: bytes) -> np.ndarray:
try:
return np.array(Image.open(io.BytesIO(contents)).convert("RGB"))
except Exception as exc:
bad_request("Upload must be a readable tile image.", exc)
def load_uploaded_rgb_image(contents: bytes) -> tuple[Image.Image, np.ndarray]:
try:
image = Image.open(io.BytesIO(contents)).convert("RGB")
except Exception as exc:
bad_request("Upload must be a readable image.", exc)
return image, np.array(image)
def normalize_room_upload(contents: bytes) -> bytes:
try:
image = Image.open(io.BytesIO(contents))
image.load()
except Exception as exc:
bad_request("Upload must be a readable image.", exc)
source_format = (image.format or "").upper()
has_alpha = image.mode in {"RGBA", "LA"} or (image.mode == "P" and "transparency" in image.info)
width, height = image.size
largest = max(width, height)
needs_resize = largest > ROOM_UPLOAD_MAX_DIMENSION
try:
orientation = image.getexif().get(274)
except Exception:
orientation = None
needs_orientation = orientation not in {None, 1}
if source_format == "JPEG" and not has_alpha and not needs_resize and not needs_orientation:
return contents
image = ImageOps.exif_transpose(image)
if has_alpha:
alpha = image.convert("RGBA")
background = Image.new("RGB", alpha.size, (255, 255, 255))
background.paste(alpha, mask=alpha.getchannel("A"))
image = background
else:
image = image.convert("RGB")
width, height = image.size
largest = max(width, height)
if largest > ROOM_UPLOAD_MAX_DIMENSION:
scale = ROOM_UPLOAD_MAX_DIMENSION / float(largest)
target_size = (
max(1, int(round(width * scale))),
max(1, int(round(height * scale))),
)
image = image.resize(target_size, Image.Resampling.LANCZOS)
buffer = io.BytesIO()
image.save(buffer, format="JPEG", quality=ROOM_UPLOAD_JPEG_QUALITY, optimize=True)
return buffer.getvalue()
|