编辑代码

import matplotlib.pyplot as plt
import numpy as np

def plot_neighbors(image, center_pixel, neighbors):
    fig, ax = plt.subplots()
    ax.imshow(image, cmap='gray', interpolation='nearest')
    
    # Highlight the center pixel
    x_center, y_center = center_pixel
    ax.scatter(x_center, y_center, color='red', s=100, zorder=5)
    
    # Highlight the neighbors
    for neighbor in neighbors:
        x_neighbor, y_neighbor = neighbor
        ax.scatter(x_neighbor, y_neighbor, color='blue', s=100, zorder=5)
    
    # Add labels and title
    ax.set_title('Center Pixel (Red) and Neighbors (Blue)')
    ax.set_xlabel('X-axis')
    ax.set_ylabel('Y-axis')
    ax.grid(True)
    
    plt.show()

# Create a sample image (a 10x10 grid of zeros)
image = np.zeros((10, 10))

# Define the center pixel
center_pixel = (5, 5)

# Calculate 4-neighbors
four_neighbors = [
    (center_pixel[0]-1, center_pixel[1]),   # Left
    (center_pixel[0]+1, center_pixel[1]),   # Right
    (center_pixel[0], center_pixel[1]-1),   # Down
    (center_pixel[0], center_pixel[1]+1)    # Up
]

# Calculate 8-neighbors
eight_neighbors = four_neighbors + [
    (center_pixel[0]-1, center_pixel[1]+1), # Top-left
    (center_pixel[0]+1, center_pixel[1]+1), # Top-right
    (center_pixel[0]-1, center_pixel[1]-1), # Bottom-left
    (center_pixel[0]+1, center_pixel[1]-1)  # Bottom-right
]

# Plotting 4-neighbors
print("Plotting 4-neighbors:")
plot_neighbors(image, center_pixel, four_neighbors)

# Plotting 8-neighbors
print("Plotting 8-neighbors:")
plot_neighbors(image, center_pixel, eight_neighbors)