在Python 3中重现Python 2 PyQt4 QImage构造函数的行为

2024-09-28 22:23:50 发布

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

我用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。在


Tags: numpyformattypegui数组argumentargumentsint
1条回答
网友
1楼 · 发布于 2024-09-28 22:23:50

在上面的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版本:

QImage(uchar * data, int width, int height, Format format)

从保存的PyQt 4.10.4文档here来看,PyQt对unsigned char *的期望在Python 2和3中是不同的:

Python 2:

If Qt expects a char *, signed char * or an unsigned char * (or a const version) then PyQt4 will accept a unicode or QString that contains only ASCII characters, a str, a QByteArray, or a Python object that implements the buffer protocol.

Python 3:

If Qt expects a signed char * or an unsigned char * (or a const version) then PyQt4 will accept a bytes.

Numpy数组满足这两个条件,但显然Numpy视图也不能满足这两个要求。实际上令人困惑的是,bdata.T在Python2中完全可以工作,因为它据称返回了一个视图:

^{pr2}$

最后的答案是:如果您需要进行转换以生成一个视图,您可以通过将结果的copy()转换为一个新数组来传递给构造函数来避免错误。这也许不是最好的答案,但它会奏效的。在

相关问题 更多 >