from PIL import Image

class ImageObject:
    def __init__(self, image: Image.Image, position: tuple):
        self.image = image  # The image segment (PIL Image)
        self.position = position  # Position of the segment (row, col)

    def show(self):
        """Display the image segment."""
        self.image.show()

    def save(self, output_path):
        """Save the image segment to a specified path."""
        self.image.save(output_path)

def split_image_to_objects(image_path: str, rows: int, cols: int) -> list:
    """Load an image, split it into segments, and return a list of ImageObject."""
    image = Image.open(image_path)  # Open the image
    width, height = image.size

    # Calculate the size of each segment
    segment_width = width // cols
    segment_height = height // rows

    image_objects = []

    for row in range(rows):
        for col in range(cols):
            # Define the bounding box for each segment
            left = col * segment_width
            upper = row * segment_height
            right = left + segment_width
            lower = upper + segment_height

            # Crop the image to get the segment
            segment = image.crop((left, upper, right, lower))
            # Create an ImageObject and append it to the list
            image_segment = ImageObject(segment, (row, col))
            image_objects.append(image_segment)

    return image_objects

# Example usage
image_path = 'source-images/logo.png'  # Replace with your image path
rows = 2  # Number of rows to split
cols = 2  # Number of columns to split

list_of_image_objects = split_image_to_objects(image_path, rows, cols)

# Show the segments or perform other operations
for i, img_obj in enumerate(list_of_image_objects):
    img_obj.show()  # Display each image segment
    img_obj.save(f'segment_{i}.png')  # Uncomment to save each segment
