File size: 2,242 Bytes
f89e218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"""
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