Spaces:
Sleeping
Sleeping
File size: 1,506 Bytes
77da9e2 |
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 |
"""
Image Utilities - Shared Image Loading Functions
This module provides utilities for loading images from various formats.
Eliminates duplication between service.py and ocr_handler.py.
"""
import cv2
import numpy as np
from PIL import Image
from typing import Union
from pathlib import Path
def load_image(image: Union[str, Path, np.ndarray, Image.Image]) -> np.ndarray:
"""
Load image from various formats
Args:
image: Image path, PIL Image, or numpy array
Returns:
Numpy array in RGB format
Raises:
ValueError: If image type is not supported
"""
if isinstance(image, (str, Path)):
# Load from file path
pil_image = Image.open(image).convert('RGB')
return np.array(pil_image)
elif isinstance(image, Image.Image):
# Convert PIL to numpy
return np.array(image.convert('RGB'))
elif isinstance(image, np.ndarray):
# Already numpy array
if len(image.shape) == 2:
# Grayscale, convert to RGB
return cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
elif image.shape[2] == 4:
# RGBA, convert to RGB
return cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
elif image.shape[2] == 3:
# Assume it's RGB if already 3 channels
return image
else:
raise ValueError(f"Unsupported image shape: {image.shape}")
else:
raise ValueError(f"Unsupported image type: {type(image)}")
|