小编Ale*_*sam的帖子

传递/返回Cython Memoryviews与NumPy Arrays

我正在编写Python代码来加速二进制图像中标记对象的区域属性函数.以下代码将根据对象的索引计算二进制图像中标记对象的边界像素数.main()函数将遍历二进制图像"mask"中的所有标记对象,并计算每个对象的边框像素数.

我想知道在这个Cython代码中传递或返回变量的最佳方法是什么.变量可以是NumPy数组,也可以是类型化的Memoryviews.我已经在绕过搞砸/在不同的格式返回变量,但不能推导出最佳/最有效的方法是什么.我是新来用Cython所以Memoryviews仍然相当抽象的我,是否有这两种方法之间的不同仍是一个谜.我正在使用的图像包含100,000多个标记对象,因此这些操作需要相当高效.

总结一下:

什么时候/我应该将我的变量作为类型化的Memoryviews而不是NumPy数组传递/返回以进行非常重复的计算?有没有最好的方式或者它们是完全一样的?

%%cython --annotate

import numpy as np
import cython
cimport numpy as np

DTYPE = np.intp
ctypedef np.intp_t DTYPE_t

@cython.boundscheck(False)
@cython.wraparound(False)
def erode(DTYPE_t [:,:] img):

    # Image dimensions
    cdef int height, width, local_min
    height = img.shape[0]
    width = img.shape[1]

    # Padded Array
    padded_np = np.zeros((height+2, width+2), dtype = DTYPE)
    cdef DTYPE_t[:,:] padded = padded_np
    padded[1:height+1,1:width+1] = img

    # Eroded image
    eroded_np = np.zeros((height,width),dtype=DTYPE)
    cdef DTYPE_t[:,:] eroded = eroded_np

    cdef DTYPE_t i,j
    for i in range(height):
        for j …
Run Code Online (Sandbox Code Playgroud)

python numpy image-processing cython memoryview

1
推荐指数
1
解决办法
821
查看次数

标签 统计

cython ×1

image-processing ×1

memoryview ×1

numpy ×1

python ×1