图像的分割之基于区域的分割
基于区域生长法的分割
import numpy as np
import cv2 as cv
# 区域生长法
def region_growth(gray, seeds, thresh=15):
# 采用8-邻域
connects = [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0)]
height, width = gray.shape
# 标记矩阵,标记所给生长点生长后的区域
seed_mark = np.zeros(gray.shape)
# 生长点列表
seed_list = []
for seed in seeds:
seed_list.append(seed)
# 如果生长点列表中还有生长点
while len(seed_list) > 0:
# 获取当前生长点
current_point = seed_list.pop(0)
# 将生长点标记为1
seed_mark[current_point[0], current_point[1]] = 1
# 对当前生长点的8-邻域进行相似性判断
for i in range(len(connects)):
current_x = current_point[0] + connects[i][0]
current_y = current_point[1] + connects[i][1]
if current_x < 0 or current_y < 0 or current_x >= height or current_y >= width:
continue
# 生长点与邻域的点的像素值之差
dist = abs(int(gray[current_x, current_y]) - int(gray[current_point[0], current_point[1]]))
# 如果生长点的8-邻域中有满足相似性准则的并且还没有被标记的点
if dist < thresh and seed_mark[current_x, current_y] == 0:
# 在标记矩阵中将该点标记为1
seed_mark[current_x, current_y] = 1
# 加入生长点列表
seed_list.append((current_x, current_y))
return seed_mark
gray = cv.imread("./watershed.jpg", cv.IMREAD_GRAYSCALE)
seeds = [(2, 2), (2, 50), (2, 100)]
result = region_grow(gray, seeds, thresh=15)
cv.imshow("img", result)
cv.waitKey(0)