python – 缺少边缘的凹面船体
作者:互联网
我有一个二进制掩码,我想从中提取轮廓.二进制掩码的所有“外部”边缘都是具有非常高概率的“真实边缘”.保持这些边缘固定,我的目标是插入“缺失”边缘(示例图像和下面所需的结果).我尝试过使用Delaunay三角测量,没有太大的成功(见下面的代码).但是,我甚至不确定这是最好的方法,因为我会在这个过程中从“真正的边缘”中丢失一些细节.
Delaunay三角剖分是否合适?如果是这样,下面的代码出了什么问题?有没有更好的算法来解决这类问题?怎么能用Python实现呢?
当前代码(不起作用)
import numpy as np
from scipy.spatial import Delaunay
from descartes import PolygonPatch
from shapely.geometry import MultiLineString
from shapely.ops import cascaded_union, polygonize
from skimage.draw import polygon
from skimage import segmentation, morphology
def triangulate(mask, alpha=1000):
contours = measure.find_contours(mask, 0.8)
points = []
for n, contour in enumerate(contours):
for m in xrange(0, len(contour[:, 0])):
y = contour[:, 0][m]
x = contour[:, 1][m]
points.append([y, x])
points = np.asarray(points)
tri = Delaunay(points)
edges = set()
edge_points = []
def add_edge(i, j):
if (i, j) in edges or (j, i) in edges: return
edges.add( (i, j) )
edge_points.append(points[ [i, j] ])
for ia, ib, ic in tri.vertices:
pa = points[ia]
pb = points[ib]
pc = points[ic]
# Lengths of sides of triangle
a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
# Semiperimeter of triangle
s = (a + b + c)/2.0
# Area of triangle by Heron's formula
try:
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
circum_r = a*b*c/(4.0*area)
# Here's the radius filter.
#if circum_r < 1.0/alpha:
if circum_r < alpha:
add_edge(ia, ib)
add_edge(ib, ic)
add_edge(ic, ia)
except:
print('Triangulation error')
m = MultiLineString(edge_points)
triangles = list(polygonize(m))
poly = PolygonPatch(cascaded_union(triangles), alpha=0.5)
vertices = poly.get_path().vertices
rr, cc = polygon(vertices[:,0], vertices[:,1])
img = np.zeros(im.shape)
img[rr, cc] = 1
return img
解决方法:
正如nikie指出的那样,如果不要求性能,morphological snakes将解决您的问题.
当你增加迭代次数时,蛇往往会完美地掩盖形状,但这不是你想要的,所以你需要弄清楚有效的参数组合.
我玩了一下,找到了一个很好的近似值:
对于这个形状,我使用以下代码:
def test_concave():
# Load the image.
imgcolor = imread("testimages/concave_hull.jpg")/255.0
img = rgb2gray(imgcolor)
# g(I)
gI = morphsnakes.gborders(img, alpha=1000, sigma=7)
# Morphological GAC. Initialization of the level-set.
mgac = morphsnakes.MorphGAC(gI, smoothing=3, threshold=0.55, balloon=-1)
mgac.levelset = circle_levelset(img.shape, (50, 199), 200)
# Visual evolution.
ppl.figure()
morphsnakes.evolve_visual(mgac, num_iters=62, background=imgcolor)
if __name__ == '__main__':
print """"""
test_concave()
ppl.show()
标签:triangulation,python,interpolation,image-processing,delaunay 来源: https://codeday.me/bug/20190725/1530231.html