How can access to pixel data with PYQt' QImage

2019-04-12 21:30发布

问题:

I need to access the pixel data in a qimage object with PyQt4.

The .pixel() is too slow so the docs say to use the scanline() method.

In c++ I can get the pointer returned by the scanline() method and read/write the pixel RGB value from the buffer.

With Python I get the SIP voidptr object that points to the pixels buffer so I can only read the pixel RGB value using bytearray but I cannot change the value in the original pointer.

Any suggestions?

回答1:

Here are some examples:

from PyQt4 import QtGui, QtCore
img = QtGui.QImage(100, 100, QtGui.QImage.Format_ARGB32)
img.fill(0xdeadbeef)

ptr = img.bits()
ptr.setsize(img.byteCount())

## copy the data out as a string
strData = ptr.asstring()

## get a read-only buffer to access the data
buf = buffer(ptr, 0, img.byteCount())

## view the data as a read-only numpy array
import numpy as np
arr = np.frombuffer(buf, dtype=np.ubyte).reshape(img.height(), img.width(), 4)

## view the data as a writable numpy array
arr = np.asarray(ptr).reshape(img.height(), img.width(), 4)