snake算法总结

article/2025/11/7 17:22:59

snake是一种主动轮廓模型,笨妞对主动轮廓模型的理解:你先给它一个初始轮廓,模型以初始轮廓为基准逐步迭代,来改进图像的轮廓,使其更加精确。主动轮廓模型目前用到了2种:CV和snake。前者没有看算法内部的原理。而snake,以最原始的论文《Snakes: Active Contour Models》为出发点。


1. snake原理

snake在逐步迭代优化过程的目标是能量函数最小化,这个能量函数指的是轮廓能量和图像能量的总和(为什么要最小化这个能量总和,还不太清楚,论文也没有具体说)。snake的目标不像sobel、canny等找到整张图的轮廓。它只搜索你给出的初始轮廓附近,达到轮廓更精确的目标,至少原版的snake只能达到局部优化的目标。

能量函数:


其中指当前轮廓本身的能量,称为内部能量,而指图像上轮廓对应点的能量,称为外部能量,应该是方差相关的项。

而内部能量由两部分构成:一阶导数的模(称为弹性能量)和二阶导数的模(弯曲能量)


为什么是这样的呢?据说是因为曲线曲率的关系,闭合的轮廓曲线中,凸曲线按照法向量的方向,具有向内的作用力;凹曲线法向量向外,具有向外的力。而曲率计算就是跟一阶导数、二阶导数相关的。很复杂,不甚理解。

在迭代过程中,弹性能量能快速的把轮廓压缩成光滑的圆;弯曲能量将轮廓拉成光滑的曲线或直线,他们的作用是保持轮廓的光滑和连续性。通常alpha越大,轮廓收敛越快;beta越大,轮廓越光滑。

外部图像能量作者分了三种:线性能量,通常更亮度相关;边缘能量,由图像的边缘组成,而边缘可以通过sobel算子计算;终端能量。

线性能量:

边缘能量:

终端(角点)能量:


通常可以根据更期望轮廓趋向于哪方面来选择以上三种能量。在迭代优化过程中,外部能量会使轮廓朝(灰度)高梯度位置靠近。而通常梯度高的位置都是图像中前景与背景的界限或者物体与物体之间、物体内部不同部分的界限,适合用于分割。


对于优化,优化的目标是总能量函数局部极小,通过能量函数极小或者迭代次数来控制迭代的终止。极小化能量函数通过欧拉方程计算解,作者在附录中用了数值方法进行推到,将欧拉方程推到为:


其中


引入外部能量:


再转化为每一步迭代演进过程:


A+ rI为五对角条带矩阵。


2. GVF snake

关于图像能量中line、edge、termatation计算其实都挺复杂的。反倒是计算梯度向量场简单一些。将图像能量由线、边缘、角点的能量替换为梯度向量场,就是GVF snake。


3. 程序

对于snake,skimage里面active_contour函数就是典型的snake算法,借用里面的实现程序:

import numpy as np
import scipy.linalg
from scipy.interpolate import RectBivariateSpline
from skimage.util import img_as_float
from skimage.filters import sobeldef active_contour(image, snake, alpha=0.01, beta=0.1,w_line=0, w_edge=1, gamma=0.01,bc='periodic', max_px_move=1.0,max_iterations=2500, convergence=0.1):"""Active contour model.Active contours by fitting snakes to features of images. Supports singleand multichannel 2D images. Snakes can be periodic (for segmentation) orhave fixed and/or free ends.The output snake has the same length as the input boundary.As the number of points is constant, make sure that the initial snakehas enough points to capture the details of the final contour.Parameters----------image : (N, M) or (N, M, 3) ndarrayInput image.snake : (N, 2) ndarrayInitialisation coordinates of snake. For periodic snakes, it shouldnot include duplicate endpoints.alpha : float, optionalSnake length shape parameter. Higher values makes snake contractfaster.beta : float, optionalSnake smoothness shape parameter. Higher values makes snake smoother.w_line : float, optionalControls attraction to brightness. Use negative values to attract todark regions.w_edge : float, optionalControls attraction to edges. Use negative values to repel snake fromedges.gamma : float, optionalExplicit time stepping parameter.bc : {'periodic', 'free', 'fixed'}, optionalBoundary conditions for worm. 'periodic' attaches the two ends of thesnake, 'fixed' holds the end-points in place, and'free' allows freemovement of the ends. 'fixed' and 'free' can be combined by parsing'fixed-free', 'free-fixed'. Parsing 'fixed-fixed' or 'free-free'yields same behaviour as 'fixed' and 'free', respectively.max_px_move : float, optionalMaximum pixel distance to move per iteration.max_iterations : int, optionalMaximum iterations to optimize snake shape.convergence: float, optionalConvergence criteria.Returns-------snake : (N, 2) ndarrayOptimised snake, same shape as input parameter.References----------.. [1]  Kass, M.; Witkin, A.; Terzopoulos, D. "Snakes: Active contourmodels". International Journal of Computer Vision 1 (4): 321(1988).Examples-------->>> from skimage.draw import circle_perimeter>>> from skimage.filters import gaussianCreate and smooth image:>>> img = np.zeros((100, 100))>>> rr, cc = circle_perimeter(35, 45, 25)>>> img[rr, cc] = 1>>> img = gaussian(img, 2)Initiliaze spline:>>> s = np.linspace(0, 2*np.pi,100)>>> init = 50*np.array([np.cos(s), np.sin(s)]).T+50Fit spline to image:>>> snake = active_contour(img, init, w_edge=0, w_line=1) #doctest: +SKIP>>> dist = np.sqrt((45-snake[:, 0])**2 +(35-snake[:, 1])**2) #doctest: +SKIP>>> int(np.mean(dist)) #doctest: +SKIP25"""max_iterations = int(max_iterations)if max_iterations <= 0:raise ValueError("max_iterations should be >0.")convergence_order = 10valid_bcs = ['periodic', 'free', 'fixed', 'free-fixed','fixed-free', 'fixed-fixed', 'free-free']if bc not in valid_bcs:raise ValueError("Invalid boundary condition.\n" +"Should be one of: "+", ".join(valid_bcs)+'.')img = img_as_float(image)
    height = img.shape[0]width = img.shape[1]RGB = img.ndim == 3# Find edges using sobel:if w_edge != 0:if RGB:edge = [sobel(img[:, :, 0]), sobel(img[:, :, 1]),sobel(img[:, :, 2])]else:edge = [sobel(img)]for i in range(3 if RGB else 1):edge[i][0, :] = edge[i][1, :]edge[i][-1, :] = edge[i][-2, :]edge[i][:, 0] = edge[i][:, 1]edge[i][:, -1] = edge[i][:, -2]else:edge = [0]# Superimpose intensity and edge images:if RGB:img = w_line*np.sum(img, axis=2) \+ w_edge*sum(edge)else:img = w_line*img + w_edge*edge[0]# Interpolate for smoothness:intp = RectBivariateSpline(np.arange(img.shape[1]),np.arange(img.shape[0]),img.T, kx=2, ky=2, s=0)x, y = snake[:, 0].astype(np.float), snake[:, 1].astype(np.float)xsave = np.empty((convergence_order, len(x)))ysave = np.empty((convergence_order, len(x)))# Build snake shape matrix for Euler equationn = len(x)a = np.roll(np.eye(n), -1, axis=0) + \np.roll(np.eye(n), -1, axis=1) - \2*np.eye(n)  # second order derivative, central differenceb = np.roll(np.eye(n), -2, axis=0) + \np.roll(np.eye(n), -2, axis=1) - \4*np.roll(np.eye(n), -1, axis=0) - \4*np.roll(np.eye(n), -1, axis=1) + \6*np.eye(n)  # fourth order derivative, central differenceA = -alpha*a + beta*b# Impose boundary conditions different from periodic:sfixed = Falseif bc.startswith('fixed'):A[0, :] = 0A[1, :] = 0A[1, :3] = [1, -2, 1]sfixed = Trueefixed = Falseif bc.endswith('fixed'):A[-1, :] = 0A[-2, :] = 0A[-2, -3:] = [1, -2, 1]efixed = Truesfree = Falseif bc.startswith('free'):A[0, :] = 0A[0, :3] = [1, -2, 1]A[1, :] = 0A[1, :4] = [-1, 3, -3, 1]sfree = Trueefree = Falseif bc.endswith('free'):A[-1, :] = 0A[-1, -3:] = [1, -2, 1]A[-2, :] = 0A[-2, -4:] = [-1, 3, -3, 1]efree = True# Only one inversion is needed for implicit spline energy minimization:inv = scipy.linalg.inv(A+gamma*np.eye(n))# Explicit time stepping for image energy minimization:for i in range(max_iterations):fx = intp(x, y, dx=1, grid=False)fy = intp(x, y, dy=1, grid=False)if sfixed:fx[0] = 0fy[0] = 0if efixed:fx[-1] = 0fy[-1] = 0if sfree:fx[0] *= 2fy[0] *= 2if efree:fx[-1] *= 2fy[-1] *= 2xn = np.dot(inv, gamma*x + fx)yn = np.dot(inv, gamma*y + fy)# Movements are capped to max_px_move per iteration:dx = max_px_move*np.tanh(xn-x)dy = max_px_move*np.tanh(yn-y)if sfixed:dx[0] = 0dy[0] = 0if efixed:dx[-1] = 0dy[-1] = 0x += dxy += dy
        x[x<0] = 0y[y<0] = 0x[x>(height-1)] = height - 1y[y>(width-1)] = width - 1# Convergence criteria needs to compare to a number of previous# configurations since oscillations can occur.j = i % (convergence_order+1)if j < convergence_order:xsave[j, :] = xysave[j, :] = yelse:dist = np.min(np.max(np.abs(xsave-x[None, :]) +np.abs(ysave-y[None, :]), 1))if dist < convergence:breakreturn np.array([x, y]).T

这个程序有个bug,没有对新计算出的轮廓做约束,这样的话如果初始snake比较靠近图像的边,那么轮廓就会溢出到图像外。红色部分是个人做的修改。


另外一个简化的gvf snake程序

file_name = '24_82_11.bmp'
#file_path = os.path.join('cell_split/23-2018-05-1708.57.22', file_name)
img = skimage.color.rgb2gray(skimage.data.imread(file_name))
f = filters.gaussian_gradient_magnitude(img,2.0)
fx = filters.gaussian_filter(f,2.0,(1,0))
fy = filters.gaussian_filter(f,2.0,(0,1))
u = fx.copy()
v = fy.copy()
mu = 0.1
for i in range(10000):m = (fx**2+fy**2)ut = mu*filters.laplace(u)-(u-fx)*mvt = mu*filters.laplace(v)-(v-fy)*mu += utv += vtt = np.linspace(0,2*np.pi,50)for t in range(5000):x2 = filters.gaussian_filter(path,1.0,(2,0),mode='wrap')x4 = filters.gaussian_filter(x2,1.0,(2,0),mode='wrap')dx = np.array([u[int(x),int(y)] for y,x in path])dy = np.array([v[int(x),int(y)] for y,x in path])delta = np.array([dx,dy]).Tpath += 0.001*x2-0.001*x4+1.0*delta#print(path.shape)path[:,0][path[:,0]>129] = 129path[:,1][path[:,1]>105] = 105
这个gvf snake基本的骨架是对的,但是太简单了,效果确实不好。






http://chatgpt.dhexx.cn/article/yAKfJNUL.shtml

相关文章

主动轮廓模型:Snake模型的python实现

质量声明&#xff1a;原创文章&#xff0c;内容质量问题请评论吐槽。如对您产生干扰&#xff0c;可私信删除。 主要参考&#xff1a;Active Contour Model — skimage v0.16.dev0 docs - scikit-image 文章目录 skimage实现函数声明代码示例结果显示 Numpy实现代码示例结果显示…

社交网络分析--python-igraph

#coding:utf-8 import scrapy import xlwt, lxml import re, json import matplotlib.pyplot as plt import numpy as np import pylab from scipy import linalg #文档&#xff1a;igraph.org/python/doc/ #社交网络分析 #from igraph import *社交网络算法介绍 分析-权利的游…

(一文读懂社交网络分析(附应用、前沿、学习资源)学习笔记)

一文读懂社交网络分析&#xff08;附应用、前沿、学习资源&#xff09;学习笔记 一、社交网络的结构特性与演化机理1、社交网络结构分析与建模1.1 统计特性1.2 网络特性1.3 网络模型 2、虚拟社区以及发现技术2.1 定义2.2 社区发现算法评估指标2.3社区静态发现算法2.4 社区动态发…

推荐系统实践读书笔记-06利用社交网络数据

推荐系统实践读书笔记-06利用社交网络数据 自从搜索引擎谷歌诞生后&#xff0c;大家都在讨论互联网的下一个金矿是什么。现在&#xff0c;几乎所有的人都认为那就是社交网络。根据尼尔森2010年的报告&#xff0c;用户在互联网上22%的时间花费在社交网站和社交媒体上。Facebook…

超级干货 :一文读懂社交网络分析(附应用、前沿、学习资源)

转自&#xff1a;http://op.inews.qq.com/m/20171020B02CN500?refer100000355&chl_codekb_news_tech&h0 本文主要阐述&#xff1a; 社交网络的结构特性与演化机理 社交网络群体行为形成与互动规律 社交网络信息传播与演化机理 社交网络分析的应用 社交网络前沿研…

社交网络分析调研上

//2019年08月15日 文章来源&#xff1a;https://mp.weixin.qq.com/s/39_r3idlE3plqJwlhrvpAQ 一、相关概述 1、定义&#xff1a;“由许多节点构成的一种社会结构&#xff0c;节点通常是指个人或者组织&#xff0c;而社交网络代表着各种社会关系。” *在之前是社会学和人类学的…

社交网络影响力最大化

目录 1、社交网络概述 2、影响力最大化问题分类 3、社交网络影响力最大化作用 4、传播模型 4.1独立级联模型&#xff08;Independent Cascade Model&#xff09;简称 IC 模型 4.2线性阈值模型&#xff08;Linear Threshold Model&#xff09;简称LT模型 社交网络影响力最…

基于hadoop的社交网络三角形计数

图的三角形计数问题是一个基本的图计算问题,是很多复杂网络分析(比如社交网络分析) 的基础。目前图的三角形计数问题已经成为了 Spark 系统中 GraphX 图计算库所提供的一个算法级 API。本次实验任务就是要在 Hadoop 系统上实现 Twitter 社交网络图的三角形计数任务。 1.1 …

PageRank算法在社交网络上的应用

PageRank算法介绍 pagerank算法的核心思想是&#xff0c;计算一个用户随机点击一个网站然后不停点击从而到达各个网站的概率。而一个网站的打开概率又取决于那些指向他自己的那些网站的概率&#xff0c;所以这个概率的计算是一个不断迭代的过程。 一个简单的例子&#xff1a;…

社交网络与社会计算课程内容梳理总结

目录 1 引言2 复杂网络的图要素3 复杂网络度量4 复杂网络模型5 网络表示学习6 主题模型 1 引言 社会计算是指社会科学和计算技术交叉融合而成的一个研究领域&#xff0c;研究如何利用计算系统帮助人们进行沟通与协作&#xff0c;研究如何利用计算技术分析社会运行的规律与发展…

图论与复杂网络建模工具Networkx的四种网络模型

Networkx的四种网络模型 一. Networkx的下载安装二. 规则图三、ER随机图四、WS小世界网络五、BA无标度网络六. 总结 NetworkX提供了4种常见网络的建模方法&#xff0c;分别是&#xff1a;规则图&#xff0c;ER随机图&#xff0c;WS小世界网络和BA无标度网络。 一. Networkx的下…

社交网络分析算法应用,社交网络分析算法

社交网络的起源&#xff0c;发展历程及未来的发展趋势。越详细越好啊&#xff0c;多谢了各位 社交网络的起源六度分割原理及社交网络的兴起与发展有一个数学领域的猜想&#xff0c;名为Six Degrees of Separation&#xff0c;中文翻译包括以下几种&#xff1a; 六度分割理论或…

PageRank与社交网络模型评估

&#xfeff;&#xfeff; SNS社交网络在近几年流行起来&#xff0c;并呈现出火爆的增长趋势。在仿制国外Facebook、twitter等成功先例的基础上&#xff0c;国内的人人网、新浪微博等一系列社交网络正风生水起。 &#xfeff; 这些社交网站表面上看起来十分普通和其他网站别无二…

基于社交网络的推荐

论文题目&#xff1a;Graph Neural Networks for Social Recommendation 文章解决的challenge&#xff1a; 1.We propose a novel graph neural network GraphRec, which can model graph data in social recommendations coherently; 将用户与物品交互矩阵&#xff0c;用户与用…

社交网络分析之关系图(原理+Python代码)

数据来源于天池赛题&#xff1a;零基础入门数据分析-学术前沿趋势分析 地址&#xff1a;https://tianchi.aliyun.com/competition/entrance/531866/information 一、原理介绍 社交网络分析是图关系挖掘的一个分支&#xff0c;通常以关系图的形式来展示人与人之间的关系网络。…

python绘制社会关系网络图_python画社交网络图

在图书馆的检索系统中&#xff0c;关于图书的信息里面有一个是图书相关借阅关系图。跟这个社交网络图是一样的&#xff0c;反映了不同对象间的关联性。利用python画社交网络图使用的库是 networkx import networkx as nx import matplotlib.pyplot as plt G nx.Graph() G.…

《关于动态社交网络建模和分析的教程》的读书笔记

** 一、The French-DeGroot model ** 1.模型介绍 描述了一个有n个个体的团体的意见形成的离散时间过程。 模型&#xff1a; x(k1)Wx(k),k0,1…&#xff08;2&#xff09;&#xff08;French提出&#xff09; &#xff08;3&#xff09; 参数含义&#xff1a; x1、x2、…xn&am…

社交网络模型

社交网络模型 1.空手道俱乐部模型 1.1 模型概述 空手道俱乐部模型是以一个34人的团体构成的网络拓扑模型&#xff0c;由于俱乐部创始人与空手道教练就学员学费产生分歧&#xff0c;导致俱乐部形成以这两人为首的两个团体。 1.2 俱乐部裂变前的图形和矩阵表示 1.2.1 俱乐部…

社交网络分析——信息传播模型(附带三个模型的python实现)

摘要&#xff1a;主要讲解一些基本的信息传播模型&#xff0c;以及IC模型、SI模型和SIR模型的python实现及可视化。 2021.10.06更新有需要的可以点击传送门 2020.09.26更新更新了SIR模型的实现&#xff0c;请点击传送门&#xff0c;就不放在这篇博客里了 2020.09.03更新更新了S…

MOODLE安装

https://baijiahao.baidu.com/s?id1648898834478394333&wfrspider&forpc