區域生長(Region Growing)是一種基於點的區域分割方法。該方法的基本思想是從一個或多個種子點開始,並根據一定的相似性標準將鄰近的像素添加到該區域中。這個過程會繼續,直到沒有更多的像素可以被添加到該區域中。
以下是使用區域生長方法進行圖像分割的 Python 範例:
from queue import Queue
def region_growing(image, seed):
"""
Segment an image using the region growing method.
Parameters:
- image: 2D numpy array representing the grayscale image
- seed: tuple representing the starting seed point (y, x)
Returns:
- segmented image
"""
height, width = image.shape
visited = np.zeros_like(image, dtype=np.uint8)
segmented = np.zeros_like(image, dtype=np.uint8)
# Directions for neighbors (8-connectivity)
directions = [(0, 1), (1, 0), (0, -1), (-1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]
# Define similarity criteria
threshold = 20
reference_value = image[seed]
# Use a queue to implement the growing process
q = Queue()
q.put(seed)
while not q.empty():
y, x = q.get()
if visited[y, x] == 1:
continue
visited[y, x] = 1
current_value = image[y, x]
# Check similarity criteria
if abs(current_value - reference_value) < threshold:
segmented[y, x] = 255
# Add neighbors to the queue
for dy, dx in directions:
ny, nx = y + dy, x + dx
if 0 <= ny < height and 0 <= nx < width:
q.put((ny, nx))
return segmented
# Seed point (y, x)
seed_point = (new_provided_img.shape[0] // 2, new_provided_img.shape[1] // 2)
# Segment the provided image using region growing
region_growing_img = region_growing(new_provided_img, seed_point)
# Display the original and region growing segmented images
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].imshow(new_provided_img, cmap='gray')
ax[0].set_title('Original Image')
ax[0].axis('off')
ax[1].imshow(region_growing_img, cmap='gray')
ax[1].set_title('Region Growing Segmented Image')
ax[1].axis('off')
plt.tight_layout()
plt.show()
如上所示,左側是您提供的原始圖像,而右側是使用區域生長方法得到的分割結果。
這個範例從圖像的中心點(種子點)開始,並根據相似性標準將鄰近的像素添加到區域中。在這個實例中,我設定的相似性閾值是20,這意味著與種子點的灰度值相差不超過20的像素會被添加到該區域中。
您可以根據需要調整種子點的位置和相似性閾值來獲得不同的分割結果。