|
| 1 | +"""Shared image decoding, resizing, and encoding helpers.""" |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +import cv2 |
| 6 | +import numpy as np |
| 7 | +from PIL import Image |
| 8 | + |
| 9 | + |
| 10 | +class ImageOutputError(Exception): |
| 11 | + """Raised when an image cannot be decoded or encoded.""" |
| 12 | + |
| 13 | + |
| 14 | +def canonical_image_format(path: str) -> str: |
| 15 | + """Return a canonical image format name for a path.""" |
| 16 | + extension = Path(path).suffix.lower().lstrip(".") |
| 17 | + aliases = {"jpeg": "jpg", "tif": "tiff"} |
| 18 | + return aliases.get(extension, extension) |
| 19 | + |
| 20 | + |
| 21 | +def image_needs_processing(src_path: str, dst_path: str, width: int) -> bool: |
| 22 | + """Return whether an image needs resizing or format conversion.""" |
| 23 | + return width > 0 or canonical_image_format(src_path) != canonical_image_format( |
| 24 | + dst_path |
| 25 | + ) |
| 26 | + |
| 27 | + |
| 28 | +def resize_image(image: np.ndarray, width: int) -> np.ndarray: |
| 29 | + """Resize an image to a width while preserving channels and aspect ratio.""" |
| 30 | + height = int(image.shape[0] * (width / image.shape[1])) |
| 31 | + if height % 2 != 0: |
| 32 | + height += 1 |
| 33 | + return cv2.resize(image, (width, height), interpolation=cv2.INTER_AREA) |
| 34 | + |
| 35 | + |
| 36 | +def transcode_image(src_path: str, dst_path: str, width: int = 0) -> None: |
| 37 | + """Decode, optionally resize, and encode an image without losing alpha.""" |
| 38 | + image = cv2.imread(src_path, cv2.IMREAD_UNCHANGED) |
| 39 | + if image is None: |
| 40 | + raise ImageOutputError(f"Failed to read image: {src_path}") |
| 41 | + image = _apply_exif_orientation(image, src_path) |
| 42 | + |
| 43 | + if width > 0: |
| 44 | + image = resize_image(image, width) |
| 45 | + |
| 46 | + destination_format = canonical_image_format(dst_path) |
| 47 | + image = _prepare_for_destination(image, destination_format) |
| 48 | + |
| 49 | + if not cv2.imwrite(dst_path, image): |
| 50 | + raise ImageOutputError( |
| 51 | + f"Failed to encode image as {Path(dst_path).suffix}" |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +def _apply_exif_orientation( |
| 56 | + image: np.ndarray, source_path: str |
| 57 | +) -> np.ndarray: |
| 58 | + """Apply EXIF orientation to decoded pixels before metadata is discarded.""" |
| 59 | + try: |
| 60 | + with Image.open(source_path) as source: |
| 61 | + orientation = int(source.getexif().get(274, 1)) |
| 62 | + except (OSError, TypeError, ValueError): |
| 63 | + orientation = 1 |
| 64 | + |
| 65 | + if orientation == 2: |
| 66 | + return cv2.flip(image, 1) |
| 67 | + if orientation == 3: |
| 68 | + return cv2.rotate(image, cv2.ROTATE_180) |
| 69 | + if orientation == 4: |
| 70 | + return cv2.flip(image, 0) |
| 71 | + if orientation == 5: |
| 72 | + return cv2.transpose(image) |
| 73 | + if orientation == 6: |
| 74 | + return cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE) |
| 75 | + if orientation == 7: |
| 76 | + return cv2.flip(cv2.transpose(image), -1) |
| 77 | + if orientation == 8: |
| 78 | + return cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE) |
| 79 | + return image |
| 80 | + |
| 81 | + |
| 82 | +def _prepare_for_destination( |
| 83 | + image: np.ndarray, destination_format: str |
| 84 | +) -> np.ndarray: |
| 85 | + """Convert channels and depth to values supported by the encoder.""" |
| 86 | + if destination_format == "jpg": |
| 87 | + return _to_uint8(_flatten_alpha_on_white(image)) |
| 88 | + if destination_format == "png" and image.dtype.type not in {np.uint8, np.uint16}: |
| 89 | + return _to_uint8(image) |
| 90 | + if destination_format in {"bmp", "webp"} and image.dtype.type is not np.uint8: |
| 91 | + return _to_uint8(image) |
| 92 | + return image |
| 93 | + |
| 94 | + |
| 95 | +def _to_uint8(image: np.ndarray) -> np.ndarray: |
| 96 | + """Scale image data to the eight-bit range required by JPEG.""" |
| 97 | + if image.dtype == np.uint8: |
| 98 | + return image |
| 99 | + if image.dtype == np.bool_: |
| 100 | + return image.astype(np.uint8) * 255 |
| 101 | + if np.issubdtype(image.dtype, np.integer): |
| 102 | + info = np.iinfo(image.dtype) |
| 103 | + scaled = ( |
| 104 | + (image.astype(np.float32) - float(info.min)) |
| 105 | + * (255.0 / float(info.max - info.min)) |
| 106 | + ) |
| 107 | + return np.clip(scaled, 0, 255).round().astype(np.uint8) |
| 108 | + |
| 109 | + finite = np.nan_to_num(image.astype(np.float32), nan=0.0) |
| 110 | + if finite.size and finite.min() >= 0 and finite.max() <= 1: |
| 111 | + finite = finite * 255.0 |
| 112 | + return np.clip(finite, 0, 255).round().astype(np.uint8) |
| 113 | + |
| 114 | + |
| 115 | +def _flatten_alpha_on_white(image: np.ndarray) -> np.ndarray: |
| 116 | + """Composite alpha-bearing images on white for JPEG output.""" |
| 117 | + if image.ndim != 3 or image.shape[2] not in {2, 4}: |
| 118 | + return image |
| 119 | + |
| 120 | + color = image[..., :-1] |
| 121 | + alpha = image[..., -1:] |
| 122 | + if np.issubdtype(image.dtype, np.integer): |
| 123 | + maximum = float(np.iinfo(image.dtype).max) |
| 124 | + else: |
| 125 | + maximum = 1.0 |
| 126 | + |
| 127 | + alpha_fraction = alpha.astype(np.float32) / maximum |
| 128 | + composited = ( |
| 129 | + color.astype(np.float32) * alpha_fraction |
| 130 | + + maximum * (1.0 - alpha_fraction) |
| 131 | + ) |
| 132 | + return np.clip(composited, 0, maximum).astype(image.dtype) |
0 commit comments