Python:使用多线程友好代码计算轮廓包围的区域

时间:2017-03-20 21:24:53

标签: python multithreading matplotlib

我想扩展this question以多线程友好的方式找到轮廓区域。

我尝试过以下代码:

    c = cntr.Cntr(Z, X_, radial)
    # Trace a contour at calc_levels
    for loop in range(len(calc_levels)):
        res = c.trace(calc_levels[loop])
        # result is a list of arrays of vertices and path codes
        # (see docs for matplotlib.path.Path)
        nseg = len(res) // 2
        segments = res[:nseg]
        area = PolyArea(segments[0][:,0], segments[0][:,1])

def PolyArea(x,y):
    return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))

其中我尝试调整here中的代码,而PolyArea的代码来自this question但是1)区域的计算不太正确2)它减慢了我的速度多线程代码。

我说该区域不正确,因为使用以下代码,我花了很长时间检查,我得到完全不同的答案。但是,这段代码绝对不兼容多线程,导致整个代码停止运行

    fig1 = plt.figure()
    ax1 = fig1.add_subplot(111)
    cs = ax1.contour(Z,X_,radial, levels = calc_levels,colors='k')
    for loop in range(len(calc_levels)):
        vs = None
        contour_ = None
        contour_ = cs.collections[loop]
        vs = contour_.get_paths()[0].vertices
        # Compute area enclosed by vertices
        features['Radial_Area_' + mystr + str(int(thisLevels[loop]*100))] = area(vs)

是否有人能够帮助我调试代码的第一部分,或编写一些更好的代码?

由于

1 个答案:

答案 0 :(得分:1)

抱歉,我没有比较喜欢。现在看同一个文件,我看到计算的区域是一样的!所以代码

c = cntr.Cntr(Z, X_, radial)
# Trace a contour at calc_levels
for loop in range(len(calc_levels)):
    res = c.trace(calc_levels[loop])
    # result is a list of arrays of vertices and path codes
    # (see docs for matplotlib.path.Path)
    nseg = len(res) // 2
    segments = res[:nseg]
    area = PolyArea(segments[0][:,0], segments[0][:,1])

def PolyArea(x,y):
    return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))

我认为应该如何工作,并且比其他代码快得多。

我稍后会删除这篇文章,让那些正在寻找时间的人看到我的答案