from PIL import Image

class ImageSegment:
    def __init__(self, segment, position):
        self.segment = segment  # The image segment (PIL Image)
        self.position = position  # The position (row, col)

def image_to_list_of_objects(image_path, rows, cols):
    # Open the image
    image = Image.open(image_path)
    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 ImageSegment object and append to the list
            image_segment = ImageSegment(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
cols = 2  # Number of columns

list_of_image_objects = image_to_list_of_objects(image_path, rows, cols)

# Optionally, display the segments or save them
for i, img_obj in enumerate(list_of_image_objects):
    img_obj.segment.show(title=f'Segment {i} at position {img_obj.position}')  # Display the segment
    # img_obj.segment.save(f'segment_{i}.jpg')  # Uncomment to save each segment
