import numpy as np def chamfer_distance_transform(image): # Define the weights for different pixel transitions weights = np.array([[1.414, 1, 1.414], [1, 0, 1], [1.414, 1, 1.414]]) # Create a distance map of the same size as the input image, initialized with a large value distance_map = np.ones_like(image) * np.inf # Initialize the queue for pixel traversal queue = [] # Step 1: Initialize the distance of background pixels to 0 and add them to the queue for i in range(image.shape[0]): for j in range(image.shape[1]): if image[i, j] == 0: distance_map[i, j] = 0 queue.append((i, j)) # Step 2: Iteratively update the distance values until the queue is empty while queue: # Pop the pixel from the queue i, j = queue.pop(0) # Iterate over the neighboring pixels for di in range(-1, 2): for dj in range(-1, 2): ni, nj = i + di, j + dj # Check if the pixel is within the image bounds if 0 <= ni < image.shape[0] and 0 <= nj < image.shape[1]: # Compute the updated distance using the predefined weights new_distance = distance_map[i, j] + weights[di + 1, dj + 1] # If the new distance is smaller, update the distance map and add the pixel to the queue if new_distance < distance_map[ni, nj]: distance_map[ni, nj] = new_distance queue.append((ni, nj)) return distance_map # Example binary image binary_image = np.array([[1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 0]]) # Compute Chamfer Distance Transform distance_map = chamfer_distance_transform(binary_image) print("Chamfer Distance Transform:") print(distance_map)