运行后,Cython代码返回错误的结果数据类型

我正在尝试实现一些我在StackOverflow上找到的代码(贷记为Most efficient way to calculate radial profile),并且发现了一些有关返回变量的问题。正在处理的密钥数据类型是一个无符号的16位整数。但是,从结果看,它们似乎比期望的要高得多。这是我的设置代码,我正在使用Visual Studio构建工具进行编译-使用GCC会更好吗?如果是这样,有人可以指出修改编译器的提示吗?

setup.py代码:

from distutils.core import setup
from Cython.Build import cythonize
import numpy

ext_options = {"compiler_directives": {"profile": True},"annotate": True}
setup(
    ext_modules = cythonize("radialAvgCython.pyx",**ext_options),include_dirs=[numpy.get_include()]
)

感谢您的时间!

编辑3:我想我可能已经发现了这个问题,该问题位于Cythonic代码的功能之一内,如下所示:

cdef void cython_radial_profile(DTYPE_IMG_t [:,:] img_view,DTYPE_t [:] r_profile_view,int xs,int ys,int x0,int y0) nogil:

        cdef int x,y,r,tmp

        for x in prange(xs):
            for y in range(ys):
                r =<int>(sqrt((x - x0)**2 + (y - y0)**2))
                tmp = img_view[x,y]

                r_profile_view[r] +=  tmp 

我相信,对于每个半径r,该值都将被添加到先前的值,并且没有求平均值;这就是为什么结果倾向于比预期大得多的原因。我将尝试找到一种平均每个r的方法,但是我认为这可能是核心问题,其结果要比其他简单的方位/径向平均代码大得多。

编辑2:据我所知,这是radialAvgCython.pyx中使用的代码,编写得很好,但是在此结果与标准径向平均值之间的结果差别很大:

import numpy as np
cimport numpy as np
cimport cython
from cython.parallel import prange
from libc.math cimport sqrt,ceil


DTYPE_IMG = np.uint16
ctypedef np.uint16_t DTYPE_IMG_t
DTYPE = np.int
ctypedef np.int_t DTYPE_t


@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
cdef void cython_radial_profile(DTYPE_IMG_t [:,int y0) nogil:

    cdef int x,tmp

    for x in prange(xs):
        for y in range(ys):
            r =<int>(sqrt((x - x0)**2 + (y - y0)**2))
            tmp = img_view[x,y]

            r_profile_view[r] +=  tmp



@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
def radial_profile(np.ndarray img,int centerX,int centerY):

    # Find and define image dimensions.
    cdef int xs,ys,r_max
    xs,ys = img.shape[0],img.shape[1]

    # Find maximum radius based on defined center and image size.
    cdef int topLeft,topRight,botLeft,botRight

    topLeft = <int> ceil(sqrt(centerX**2 + centerY**2))
    topRight = <int> ceil(sqrt((xs - centerX)**2 + (centerY)**2))
    botLeft = <int> ceil(sqrt(centerX**2 + (ys-centerY)**2))
    botRight = <int> ceil(sqrt((xs-centerX)**2 + (ys-centerY)**2))

    r_max = max(topLeft,botRight)

    # Create relevant variables and feed in,solve.
    cdef np.ndarray[DTYPE_t,ndim=1] r_profile = np.zeros([r_max],dtype=DTYPE)
    cdef DTYPE_t [:] r_profile_view = r_profile
    print(r_profile)
    cdef DTYPE_IMG_t [:,:] img_view = img

    with nogil:
        cython_radial_profile(img_view,r_profile_view,xs,centerX,centerY)

    # Return radial profile.
    print(r_profile)
    return r_profile

编辑:我应该提到我正在使用PyCharm作为我的IDE。

planes007 回答:运行后,Cython代码返回错误的结果数据类型

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3164299.html

大家都在问