from PIL import Image
from pylab import *
def region_growth():
print("循环增长,直到len(region_points) = 0")
count = 0
x = [-1, 0, 1, -1, 1, -1, 0, 1]
y = [-1, -1, -1, 0, 0, 1, 1, 1]
while len(region_points) > 0:
if count == 0:
point = region_points.pop(0)
i = point[0]
j = point[1]
print("len = ", len(region_points))
p_val = input_arr[i][j]
# 像素强度差异范围 + - 8
lt = p_val - 8
ht = p_val + 8
for k in range(8):
if seg_img[i + x[k]][j + y[k]] != 1:
try:
if lt < input_arr[i + x[k]][j + y[k]] < ht:
seg_img[i + x[k]][j + y[k]] = 1
p = [0, 0]
p[0] = i + x[k]
p[1] = j + y[k]
if p not in region_points:
if 0 < p[0] < rows and 0 < p[1] < columns:
# 满足条件的点
region_points.append([i + x[k], j + y[k]])
else:
seg_img[i + x[k]][j + y[k]] = 0
except IndexError:
continue
point = region_points.pop(0)
i = point[0]
j = point[1]
count = count + 1
# region_growth(point[0], point[1])
if __name__ == "__main__":
input_img = Image.open("input1.jpg").convert("L")
input_arr = np.asarray(input_img)
rows, columns = np.shape(input_arr)
plt.figure()
plt.imshow(input_img)
plt.gray()
print("请选择初始点...")
p_seed = plt.ginput(1)
print(p_seed[0][0], p_seed[0][1])
# 可以手动设置种子点
# x = int(120)
# y = int(160)
x = int(p_seed[0][0])
y = int(p_seed[0][1])
seed_pixel = [x, y]
print("选择的点为:", seed_pixel)
plt.close()
seg_img = np.zeros((rows + 1, columns + 1))
seg_img[seed_pixel[0]][seed_pixel[1]] = 255.0
img_display = np.zeros((rows, columns))
region_points = [[x, y]]
region_growth()
plt.imsave("result.jpg", seg_img)
plt.figure()
plt.imshow(seg_img)
plt.colorbar()
plt.show()
本方法不确定性较大,不同起始点迭代有不同的收敛结果,也可能不会收敛,并且收敛时间也具有不确定性。