6

我想将 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 来做到这一点。

EDIT2:在 pygame 中,有一个遮罩对象可以在 0.025 毫秒内完成我所需要的工作,而我的解决方案需要 35 毫秒,而我在互联网上某处找到的 find_contours 可以在 4-5 毫秒内完成。我将修改 pygame.mask.outline 的源代码以使用 numpy 数组并将其发布在这里。

4

2 回答 2

4

这是:获取二进制 numpy 数组轮廓的极快方法。

大纲.py:

from scipy.weave import inline, converters

_code = open("outline.c", "r").read()

def outline(data, every):
    width, height = data.shape
    return inline(_code, ['data', 'width', 'height', 'every'], type_converters=converters.blitz)

大纲.c:

/*
Modifioitu pygame.mask.Mask.outline
Input: data, width, height, every
*/

PyObject *plist, *value;
int x, y, e, firstx, firsty, secx, secy, currx, curry, nextx, nexty, n;
int a[14], b[14];
a[0] = a[1] = a[7] = a[8] = a[9] = b[1] = b[2] = b[3] = b[9] = b[10] = b[11]= 1;
a[2] = a[6] = a[10] = b[4] = b[0] = b[12] = b[8] = 0;
a[3] = a[4] = a[5] = a[11] = a[12] = a[13] = b[5] = b[6] = b[7] = b[13] = -1;

plist = NULL;
plist = PyList_New (0);
/*if (!plist) En ymmärrä mihin tätä tarvii
    return NULL;*/

every = 1;
n = firstx = firsty = secx = x = 0;

/*if(!PyArg_ParseTuple(args, "|i", &every)) {
    return NULL;
}

 by copying to a new, larger mask, we avoid having to check if we are at
   a border pixel every time.  
bitmask_draw(m, c, 1, 1); */

e = every;

/* find the first set pixel in the mask */
for (y = 1; y < height-1; y++) {
    for (x = 1; x < width-1; x++) {
        if (data(x, y)) {
             firstx = x;
             firsty = y;
             value = Py_BuildValue("(ii)", x-1, y-1);
             PyList_Append(plist, value);
             Py_DECREF(value);
             break;
        }
    }
    if (data(x, y))
        break;
}



/* covers the mask having zero pixels or only the final pixel
Pikseleitä on ainakin kymmenen
if ((x == width-1) && (y == height-1)) {
    return plist;
}        */

/* check just the first pixel for neighbors */
for (n = 0;n < 8;n++) {
    if (data(x+a[n], y+b[n])) {
        currx = secx = x+a[n];
        curry = secy = y+b[n];
        e--;
        if (!e) {
            e = every;
            value = Py_BuildValue("(ii)", secx-1, secy-1);
            PyList_Append(plist, value);
            Py_DECREF(value);
        }
        break;
    }
}       

/* if there are no neighbors, return
Pikseleitä on ainakin kymmenen
if (!secx) {
    return plist;
}*/

/* the outline tracing loop */
for (;;) {
    /* look around the pixel, it has to have a neighbor */
    for (n = (n + 6) & 7;;n++) {
        if (data(currx+a[n], curry+b[n])) {
            nextx = currx+a[n];
            nexty = curry+b[n];
            e--;
            if (!e) {
                e = every;
                if ((curry == firsty && currx == firstx) && (secx == nextx && secy == nexty)) {
                    break;
                }
                value = Py_BuildValue("(ii)", nextx-1, nexty-1);
                PyList_Append(plist, value);
                Py_DECREF(value);
            }
            break;
        }
    }
    /* if we are back at the first pixel, and the next one will be the
       second one we visited, we are done */
    if ((curry == firsty && currx == firstx) && (secx == nextx && secy == nexty)) {
        break;
    }

    curry = nexty;
    currx = nextx;
}

return_val = plist;
于 2013-01-08T20:03:42.770 回答
1

“我想将 2d numpy 数组转换为多边形” - 你能澄清一下吗?你的意思是你想要一个只有边缘元素的标记数组(在原始网格上),还是一个多边形顶点坐标的有序列表?

例如:这样做

[ [ 0, 0, 0, 0, 0 ], 
  [ 0, 1, 1, 1, 0 ], 
  [ 0, 1, 1, 1, 0 ], 
  [ 0, 1, 1, 1, 0 ], 
  [ 0, 0, 0, 0, 0 ] ]

变成这样:

[ [ 0, 0, 0, 0, 0 ], 
  [ 0, 1, 1, 1, 0 ], 
  [ 0, 1, 0, 1, 0 ], 
  [ 0, 1, 1, 1, 0 ], 
  [ 0, 0, 0, 0, 0 ] ]

或进入顶点列表( (1, 1), (3,1), (3,3), (1,3) )

或者你想先找到边然后找到顶点?

我将基于您想要的只是边缘的假设简要回答(因为您正在谈论侵蚀等)。听起来您正在尝试使用形态学操作(侵蚀等)进行边缘检测。边缘检测也可以直接进行。使用ndimage.sobelor scikits.filter.canny,或者这个:

import numpy as np
import scipy.ndimage as ndimage
import matplotlib.pyplot as pyplot
im = np.zeros((32, 32))
im[8:-8, 8:-8] = 1
im = ndimage.rotate(im, 15)
im = numpy.where(im > 0.5, 1, 0)
edges = (ndimage.filters.maximum_filter(im, size=2) == ndimage.filters.minimum_filter(im, size=2))
pyplot.imshow(edges, interpolation='nearest')
pyplot.show()

如果您的数据已经被阈值化(0 和 1)并且边缘没有过度嘈杂,那么任何边缘检测器都可以很好地工作。

于 2013-01-02T06:39:29.593 回答