To create a clean medial axis that connects the points in a reasonable order, one approach is to simplify the computation and visualization process by using the skeletonize method from the skimage library, which is well-suited for obtaining the skeleton (or medial axis) of binary images. This method will automatically generate a more connected and clean skeleton of the shape, which can be seen as an approximation of the medial axis and is often sufficient for many applications, including as a basis for defining a bone structure for animation.
First, ensure you have the necessary library installed:
Here’s how you can modify the script to use skeletonize from skimage to get a cleaner, connected medial axis:
import matplotlib.pyplot as plt
from skimage.morphology import skeletonize
binary_image = np.zeros((100, 100), dtype=bool)
binary_image[30:-30, 30:-30] = True # Example shape
# Compute the skeleton of the binary image
skeleton = skeletonize(binary_image)
# Function to plot the skeleton
def plot_skeleton(skeleton):
ax.imshow(skeleton, cmap='gray')
ax.axis('off') # Remove axis ticks and labels
This script will display a clean, connected representation of the medial axis for the given binary shape. The skeletonize function does an excellent job of thinning the shape to its medial axis while preserving the topology and connectivity of the shape, which is what you’re looking for when creating a bone structure for animation.
For converting this skeleton into a bone structure, you would then iterate over the pixels in the skeleton, identifying junction points (where more than two pixels are connected) as potential joints and end-points (where only one pixel is connected) as potential ends of bones. You can use image processing techniques to find these points and then define bones as the lines connecting these points. This will require some additional logic to navigate the skeleton and extract a hierarchical structure suitable for your animation system.
This approach provides a visually clean and connected medial axis, but turning it into a functional bone structure for animation still requires careful consideration of the specific needs of your animation framework, including how bones are weighted and how they influence the mesh during deformation.