我用PyQt4编写了一个小GUI,它显示一个图像并获得用户单击的点坐标。我需要以灰度显示2D numpy数组,所以我从数组创建一个QImage,然后从这个数组创建一个QPixmap。在python2中它工作得很好。在
但是,当我迁移到Python 3时,它无法决定QImage的构造函数-它给出了以下错误:
TypeError: arguments did not match any overloaded call:
QImage(): too many arguments
QImage(QSize, QImage.Format): argument 1 has unexpected type 'numpy.ndarray'
QImage(int, int, QImage.Format): argument 1 has unexpected type 'numpy.ndarray'
QImage(str, int, int, QImage.Format): argument 1 has unexpected type 'numpy.ndarray'
QImage(sip.voidptr, int, int, QImage.Format): argument 1 has unexpected type 'numpy.ndarray'
QImage(str, int, int, int, QImage.Format): argument 1 has unexpected type 'numpy.ndarray'
QImage(sip.voidptr, int, int, int, QImage.Format): argument 1 has unexpected type 'numpy.ndarray'
QImage(list-of-str): argument 1 has unexpected type 'numpy.ndarray'
QImage(str, str format=None): argument 1 has unexpected type 'numpy.ndarray'
QImage(QImage): argument 1 has unexpected type 'numpy.ndarray'
QImage(object): too many arguments
据我所知,我之前调用的QImage构造函数是其中之一:
QImage(str, int, int, QImage.Format)
QImage(sip.voidptr, int, int, QImage.Format)
我假设numpy数组符合其中一个协议。我认为这可能与数组和视图有关,但是我尝试过的所有变体要么产生上述错误,要么干脆不做任何操作就退出GUI。如何在python3中重现python2的行为?
下面是一个小示例,其中相同的代码在Python 2下可以正常工作,但Python 3却不行:
^{pr2}$我在Windows7上使用Anaconda安装64位,Qt4.8.7,PyQt 4.10.4,Numpy1.9.2。在
在上面的PyQt构造函数中,从名为
bdata
的Numpy数组中观察到以下行为:bdata
对python2和python3都能正常工作bdata.T
适用于2,而不是3(构造函数错误)bdata.T.copy()
对两者都有效bdata[::-1,:]
对2或3都不起作用(相同的错误)bdata[::-1,:].copy()
对两者都有效bdata[::-1,:].base
对这两者都有效,但会丢失反向操作的结果正如@ekhurvo在评论中提到的,您需要一些支持Pythonbuffer protocol的东西。这里真正感兴趣的Qt构造函数是thisQImage构造函数,或者它的const版本:
从保存的PyQt 4.10.4文档here来看,PyQt对
unsigned char *
的期望在Python 2和3中是不同的:Python 2:
Python 3:
Numpy数组满足这两个条件,但显然Numpy视图也不能满足这两个要求。实际上令人困惑的是,
^{pr2}$bdata.T
在Python2中完全可以工作,因为它据称返回了一个视图:最后的答案是:如果您需要进行转换以生成一个视图,您可以通过将结果的
copy()
转换为一个新数组来传递给构造函数来避免错误。这也许不是最好的答案,但它会奏效的。在相关问题 更多 >
编程相关推荐