我想将一个2d的numpy数组转换成多边形。性能对我来说非常重要,但是我不想创建一个C扩展程序。可以使用腐蚀创建一个二值轮廓图像。然后我找到了这个。它速度太慢并且有时无法处理腐蚀产生的尖峰。
000100
000100
000100
111011
我的第一次尝试:
mat = mat.copy() != 0
mat = mat - scipy.ndimage.binary_erosion(mat)
vertices = np.argwhere(mat)
minx = vertices.min(axis=0)[0]
maxx = vertices.max(axis=0)[0]
vertices_sorted = {}
for x in xrange(minx - 1, maxx + 2):
vertices_sorted[x] = []
for vertex in vertices:
vertices_sorted[vertex[0]].append(vertex[1])
vertex_loop = [(minx, vertices_sorted[minx][0])]
while True:
x, y = vertex_loop[-1]
for column, row in ((x, y + 1), (x, y - 1),
(x + 1, y), (x + 1, y + 1), (x + 1, y - 1),
(x - 1, y), (x - 1, y + 1), (x - 1, y - 1)):
if row in vertices_sorted[column]:
vertices_sorted[column].remove(row)
vertex_loop.append((column, row))
break
else:
vertex_loop.pop()
if vertex_loop[-1] == vertex_loop[0]:
break
return vertex_loop[:-1]
它大多数时候都能工作,但速度不够快。 我的第二段代码很少起作用,但我还没有修复它,因为它比第一段代码慢多倍:
mat = mat.copy() != 0
mat = mat - scipy.ndimage.binary_erosion(mat)
xs, ys = np.nonzero(mat)
ys = np.ma.array(ys)
vertex_loop = [(xs[0], ys[0])]
ys[0] = np.ma.masked
while True:
x, y = vertex_loop[-1]
start = np.searchsorted(xs, x-1, side="left")
end = np.searchsorted(xs, x+1, side="right")
for i in xrange(start, end):
if ys[i] == y or ys[i] == y + 1 or ys[i] == y - 1:
vertex_loop.append((xs[i], ys[i]))
ys[i] = np.ma.masked
break
else:
if np.all(ys.mask):
break
else:
vertex_loop.pop()
return vertex_loop
如何进一步提高速度?
编辑:似乎numpy掩码数组非常慢。这个实现几乎与第一个实现一样快:
#import time
#t1 = time.time()
mat = mat.copy() != 0
mat = mat - scipy.ndimage.binary_erosion(mat)
xs, ys = np.nonzero(mat)
#t2 = time.time()
minx = xs[0]
maxx = xs[-1]
# Ketju pakosti käy läpi kaikki rivit minx:n ja maxx:n välissä, sillä se ON KETJU
xlist = range(minx - 1, maxx + 2)
# starts ja ends ovat dictit jotka kertovat missä slicessä x == key
tmp = np.searchsorted(xs, xlist, side="left")
starts = dict(zip(xlist, tmp))
tmp = np.searchsorted(xs, xlist, side="right")
ends = dict(zip(xlist, tmp))
unused = np.ones(len(xs), dtype=np.bool)
#t3 = time.time()
vertex_loop = [(xs[0], ys[0])]
unused[0] = 0
count = 0
while True:
count += 1
x, y = vertex_loop[-1]
for i in xrange(starts[x - 1], ends[x + 1]):
row = ys[i]
if unused[i] and (row == y or row == y + 1 or row == y - 1):
vertex_loop.append((xs[i], row))
unused[i] = 0
break
else:
if abs(x - xs[0]) <= 1 and abs(y - ys[0]) <= 1:
break
else:
vertex_loop.pop()
#t4 = time.time()
#print abs(t1-t2)*1000, abs(t2-t3)*1000, abs(t3-t4)*1000
return vertex_loop
我想知道是否有一种使用scipy的简单方法可以实现这一点,而我没有发现它。
编辑2:在pygame中,有一个掩码对象,可以在0.025毫秒内完成我所需的操作,而我的解决方案需要35毫秒和我在互联网上找到的find_contours函数则只需要4-5毫秒。我将修改pygame.mask.outline的源代码,以使用numpy数组,并在此处发布。