使用cython会产生错误(methodobject.c),但纯python实现可以工作

2024-03-28 18:51:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下类用于使用和操纵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

我也不明白为什么,我试着和布德一起走过,但一切都很好。你知道吗

编译的*.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,当方法参数无效时,这个错误似乎是作为默认值出现的(通过PyObject_Call中的PyErr_BadInternalCall();)。但我的C语言知识太有限了,无法准确地理解这里到底发生了什么。你知道吗

有什么想法吗?你知道吗

谢谢你

杰克


Tags: pathkeyinimageselfreturnvaluedef