File size: 2,067 Bytes
0c243c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3088e3c
 
 
 
0c243c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
from PIL import Image
import config

def preprocess_image(image, target_size=512):
        """

        Preprocess the input image: resize and ensure it's RGB.



        Parameters:

        -----------

        image : PIL.Image or np.ndarray

            Input image

        target_size : int

            Target size for the image (will be square)



        Returns:

        --------

        np.ndarray : Preprocessed image

        """
        if isinstance(image, np.ndarray):
            image = Image.fromarray(image)

        # Convert to RGB if needed
        if image.mode != 'RGB':
            image = image.convert('RGB')

        # Resize to target size (square)
        image = image.resize((target_size, target_size))

        return np.array(image)

def divide_into_grid(image):
    """

    Divide image into a grid of cells.



    Parameters:

    -----------

    image : np.ndarray

        Input image



    Returns:

    --------

    list : List of cell information (row, col, cell_array, avg_color)

    """
    height, width = image.shape[:2]
    grid_h, grid_w = config.grid_size

    cell_height = height // grid_h
    cell_width = width // grid_w

    cells = []

    try : 
        cells = image.reshape(grid_h, cell_height, grid_w, cell_width, 3)
    except Exception: 
         raise TypeError("Image too big! The Grid doesn't divide the resized image evenly due to cascading rounding")
    cells = cells.transpose(0, 2, 1, 3, 4)
    cells = cells.reshape(-1, cell_height, cell_width, 3)
    #may return errors, double check after optimizing compute average colors

    vectorized = np.vectorize(compute_average_color, signature='(i,j,k)->(n)')
    cells = vectorized(cells)
    return cells

def compute_average_color(cell):
    """

    Compute the average color of a cell.



    Parameters:

    -----------

    cell : np.ndarray

        Image cell



    Returns:

    --------

    np.ndarray : Average RGB color

    """

    return np.mean(cell, axis=(0,1))