使用cython会产生错误(methodobject.c)但纯python实现会起作用

时间:2013-09-10 19:44:07

标签: python cython

我有以下类使用pygame来使用和操作图像:

class Image:
    def __init__(self,file_path=None, width=0, height=0):
        try:
            self.image = pygame.image.load(file_path)
        except:
            raise IOError
        self.width = self.image.get_size()[0]
        self.height = self.image.get_size()[1]

    def copy(self):
        return Image(0, 0, self.file_path)

    def __getitem__(self, key):
        x, y = key
        internal_pxarray = pygame.PixelArray(self.image)
        rgb_int = internal_pxarray[x][y]
        rgb = self.image.unmap_rgb(rgb_int)
        if len(rgb) == 4:
            return rgb[:-1]
        elif len(rgb) == 3:
            return rgb
        else:
            return None

    def __setitem__(self, key, value):
        internal_pxarray = pygame.PixelArray(self.image)
        x, y = key
        internal_pxarray[x][y] = pygame.Color(value[0], value[1], value[2])
        self.image = internal_pxarray.make_surface()

我这样使用:

image = Image('test.bmp')
window.displayImage(image)
for x in range(0, image.width):
    for y in range(0, image.height):
        ...
        image[x, y] = 250, 218, 221

我试图通过在包含Image类的模块上使用cython来加快速度,但是当我运行代码时,此行internal_pxarray[x][y] = pygame.Color(value[0], value[1], value[2])似乎会导致以下错误:

Traceback (most recent call last):
  File "../pink.py", line 13, in <module>
    image[x, y] = 250, 218, 221
  File "imgproc.py", line 51, in imgproc.Image.__setitem__ (imgproc.c:2256)
    self.image = internal_pxarray.make_surface()
SystemError: /Users/sysadmin/build/v2.7.3/Objects/methodobject.c:120: bad argument to internal function

而且我无法弄清楚为什么,我已经尝试过pudb,但一切似乎都很好。

编译的* .c文件中的相应行是__pyx_t_6 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;}

查看methodobject.c,当方法参数无效时,似乎将此错误提升为默认值(PyErr_BadInternalCall();中的PyObject_Call。但我的C知识太受限制了想想我们到底发生了什么。

任何想法?

谢谢,

杰克

0 个答案:

没有答案