Reproduce Python 2 PyQt4 QImage constructor behavior in Python 3

你。 提交于 2019-12-08 09:00:33

In the PyQt constructor above, the following behavior is observed from a Numpy array called bdata:

  • bdata works correctly for both Python 2 and Python 3
  • bdata.T works for 2, not for 3 (constructor error)
  • bdata.T.copy() works for both
  • bdata[::-1,:] does not work for either 2 or 3 (the same error)
  • bdata[::-1,:].copy() works for both
  • bdata[::-1,:].base works for both, but loses the result of the reverse operation

As mentioned by @ekhumoro in the comments, you need something which supports the Python buffer protocol. The actual Qt constructor of interest here is this QImage constructor, or the const version of it:

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

From the PyQt 4.10.4 documentation kept here, what PyQt expects for an unsigned char * is different in Python 2 and 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.

A Numpy array satisfies both of these, but apparently a Numpy view doesn't satisfy either. It's actually baffling that bdata.T works at all in Python 2, as it purportedly returns a view:

>>> a = np.ones((2,3))
>>> b = a.T
>>> b.base is a
True

The final answer: If you need to do transformations that result in a view, you can avoid errors by doing a copy() of the result to a new array for passing into the constructor. This may not be the best answer, but it will work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!