python - 在 python 中导入我的 cythonized 包

标签 python numpy cython distutils

我有一个包含单个函数的 script_function_cython.pyx 文件:

import numpy as np
import scipy.misc as misc
import matplotlib.pyplot as plt

def my_function(img, kernel):

    assert kernel.shape==(3, 3)

    res = np.zeros(img.shape)

    for i in range(1, img.shape[0]-1):
        for j in range(1, img.shape[1]-1):

            res[i, j] = np.sum(np.array([[img[i-1, j-1], img[i-1, j], img[i-1, j+1]],
                                 [img[i, j-1], img[i, j], img[i, j+1]],
                                [img[i+1, j], img[i+1, j], img[i+1, j+1]]])*kernel)

    return res






if __name__ == '__main__':

    kernel = np.array([[-1, -1, -1], [-1, 3, -1], [-1, -1, -1]])
    img = misc.face()[:256, :256, 0]
    res = my_function(img, kernel)

    plt.figure()
    plt.imshow(res, cmap=plt.cm.gray)

我因此创建了一个 setup.py 文件:

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

setup(
    ext_modules = cythonize('script_function_cython.pyx'),  
)

然后,我编译它:

python setup.py build_ext --inplace

并安装它:

python setup.py install

但是,当我尝试进一步导入它时,

import script_function_cython

我得到:

ImportError: No module named script_function_cython

最佳答案

使用--inplace构建不需要安装。不过,您需要从项目目录导入。

python setup.py build --inplace
python -c 'import script_function_cython'

应该不会引发错误。

关于python - 在 python 中导入我的 cythonized 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39817572/

相关文章:

python - 不要记录 'Certificate did not match expected hostname' 错误消息

python - PyCharm Idea 中的 Jenkinsfile 语法高亮显示

python - 计算按前两列中的索引分组的 numpy 数组条目的第 N 列的总和?

python - 我可以将 Cython 代码转换为 Python 吗?

python - 为什么我的代码没有删除内部矩形

python - #!/bin/sh vs #!/usr/local/bin/python 在可执行文件中

python - python中有没有像r中的 `lag.plot1`这样的方法?

python - 用 Numba 优化整组元组的字典?

python - 使用一维列索引数组切片并填充二维数组

python - 使用类似的语法将使用 MATLAB 创建的矩阵转换为 Numpy 数组