CU1-X / detection /image_utils.py
AI-DrivenTesting's picture
init
77da9e2
"""
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)}")