Spaces:
Sleeping
Sleeping
| """ | |
| Utility functions for image processing and data handling. | |
| """ | |
| import os | |
| import shutil | |
| import tempfile | |
| from PIL import Image | |
| import numpy as np | |
| def create_thumbnail(image_path, max_size=(200, 200)): | |
| """ | |
| Create a thumbnail of an image. | |
| Args: | |
| image_path: path to the image file | |
| max_size: maximum size of the thumbnail as (width, height) | |
| Returns: | |
| PIL.Image: thumbnail image | |
| """ | |
| try: | |
| image = Image.open(image_path) | |
| image.thumbnail(max_size) | |
| return image | |
| except Exception as e: | |
| print(f"Error creating thumbnail for {image_path}: {e}") | |
| return None | |
| def create_temp_directory(): | |
| """ | |
| Create a temporary directory for storing intermediate files. | |
| Returns: | |
| str: path to the temporary directory | |
| """ | |
| temp_dir = tempfile.mkdtemp(prefix="image_evaluator_") | |
| return temp_dir | |
| def cleanup_temp_directory(temp_dir): | |
| """ | |
| Clean up a temporary directory. | |
| Args: | |
| temp_dir: path to the temporary directory | |
| """ | |
| if os.path.exists(temp_dir): | |
| shutil.rmtree(temp_dir) | |
| def ensure_directory(directory): | |
| """ | |
| Ensure that a directory exists, creating it if necessary. | |
| Args: | |
| directory: path to the directory | |
| Returns: | |
| str: path to the directory | |
| """ | |
| os.makedirs(directory, exist_ok=True) | |
| return directory | |
| def is_valid_image(file_path): | |
| """ | |
| Check if a file is a valid image. | |
| Args: | |
| file_path: path to the file | |
| Returns: | |
| bool: True if the file is a valid image, False otherwise | |
| """ | |
| try: | |
| with Image.open(file_path) as img: | |
| img.verify() | |
| return True | |
| except: | |
| return False | |
| def convert_to_rgb(image_path): | |
| """ | |
| Convert an image to RGB mode if necessary. | |
| Args: | |
| image_path: path to the image file | |
| Returns: | |
| numpy.ndarray: RGB image array | |
| """ | |
| try: | |
| image = Image.open(image_path) | |
| if image.mode != 'RGB': | |
| image = image.convert('RGB') | |
| return np.array(image) | |
| except Exception as e: | |
| print(f"Error converting image to RGB: {e}") | |
| return None | |