import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from skimage.morphology import binary_erosion, disk
from skimage import io, color, filters
from skimage.data import camera

# Create a complex shape (binary image)
def create_complex_shape():
    # Load the image
    image = camera()
    
    # Convert to grayscale
    gray_image = image# color.rgb2gray(image)
    
    # Apply a threshold to binarize the image
    threshold = filters.threshold_otsu(gray_image)
    binary_image = gray_image < threshold
    
    return binary_image

# Generate the initial shape
complex_shape = create_complex_shape()

# Erosion function
def erode_shape(shape, radius):
    selem = disk(radius)
    return binary_erosion(shape, selem)

# Prepare the figure
fig, ax = plt.subplots(figsize=(6, 6))
ax.axis('off')
im = ax.imshow(complex_shape, cmap='gray', origin='upper', interpolation='none')

# Animation function
def update(frame):
    eroded_shape = erode_shape(complex_shape, frame)
    im.set_data(eroded_shape)
    ax.set_title(f"Erosion with a disk, radius: {frame}", fontsize=12)
    return im,

# Create the animation
frames = range(0, 50, 1)  # Radius increases from 0 to 30
ani = FuncAnimation(fig, update, frames=frames, interval=200)

if True:
    ani.save("mathematical-morphology-operators.mp4", writer="ffmpeg", fps=4)

# Save or display the animation
plt.show()
