您需要气球力添加到 Snakes。
Snake 的算法被定义为最小化 3 种能量 - 连续性、曲率和梯度,对应于代码中的 alpha、beta 和 gamma。当点(在曲线上)被拉得越来越近(即收缩)时,前两个(统称为内部能量)会最小化。如果它们膨胀,那么能量就会增加,这是蛇算法所不允许的。
但这个 1987 年提出的初始算法存在一些问题。问题之一是在平坦区域(梯度为零),算法无法收敛并且什么都不做。提出了几个修改来解决这个问题。这里感兴趣的解决方案是 - LD Cohen 在 1989 年提出的 Balloon Force。
气球力在图像的非信息区域中引导轮廓,即图像梯度太小而无法将轮廓推向边界的区域。负值将缩小轮廓,而正值将扩大这些区域的轮廓。将此设置为零将禁用气球力。
另一个改进是 - Morphological Snakes,它在二进制数组上使用形态运算符(例如膨胀或腐蚀),而不是在浮点数组上求解 PDE,这是活动轮廓的标准方法。这使得 Morphological Snakes 比它们的传统对应物更快且在数值上更稳定。
使用上述两个改进的 Scikit-image 的实现是morphological_geodesic_active_contour。它有一个参数balloon
在没有任何真实原始图像的情况下,让我们创建一个玩具图像并使用它:
import numpy as np
import matplotlib.pyplot as plt
from skimage.segmentation import morphological_geodesic_active_contour, inverse_gaussian_gradient
from skimage.color import rgb2gray
from skimage.util import img_as_float
from PIL import Image, ImageDraw
im = Image.new('RGB', (250, 250), (128, 128, 128))
draw = ImageDraw.Draw(im)
draw.polygon(((50, 200), (200, 150), (150, 50)), fill=(255, 255, 0), outline=(0, 0, 0))
im = np.array(im)
im = rgb2gray(im)
im = img_as_float(im)
plt.imshow(im, cmap='gray')
这给了我们下面的图片
现在让我们创建一个函数来帮助我们存储迭代:
def store_evolution_in(lst):
"""Returns a callback function to store the evolution of the level sets in
the given list.
"""
def _store(x):
lst.append(np.copy(x))
return _store
此方法需要对图像进行预处理以突出轮廓。这可以使用函数inverse_gaussian_gradient 来完成,尽管用户可能想要定义自己的版本。 MorphGAC 分割的质量很大程度上取决于这个预处理步骤。
gimage = inverse_gaussian_gradient(im)
下面我们定义我们的起点 - 一个正方形。
init_ls = np.zeros(im.shape, dtype=np.int8)
init_ls[120:-100, 120:-100] = 1
列出用于绘制演化的中间结果
evolution = []
callback = store_evolution_in(evolution)
现在 morphological_geodesic_active_contour 所需的幻线如下:
ls = morphological_geodesic_active_contour(gimage, 50, init_ls,
smoothing=1, balloon=1,
threshold=0.7,
iter_callback=callback)
现在让我们绘制结果:
fig, axes = plt.subplots(1, 2, figsize=(8, 8))
ax = axes.flatten()
ax[0].imshow(im, cmap="gray")
ax[0].set_axis_off()
ax[0].contour(ls, [0.5], colors='b')
ax[0].set_title("Morphological GAC segmentation", fontsize=12)
ax[1].imshow(ls, cmap="gray")
ax[1].set_axis_off()
contour = ax[1].contour(evolution[0], [0.5], colors='r')
contour.collections[0].set_label("Starting Contour")
contour = ax[1].contour(evolution[5], [0.5], colors='g')
contour.collections[0].set_label("Iteration 5")
contour = ax[1].contour(evolution[-1], [0.5], colors='b')
contour.collections[0].set_label("Last Iteration")
ax[1].legend(loc="upper right")
title = "Morphological GAC Curve evolution"
ax[1].set_title(title, fontsize=12)
plt.show()
红色方块是我们的起点(初始轮廓),蓝色轮廓来自最终迭代。