将 PyQt5 QPixmap 转换为 numpy ndarray

ing*_*var 7 python numpy pyqt qpixmap pyqt5

我有像素图:

pixmap = self._screen.grabWindow(0,
                                 self._x, self._y,
                                 self._width, self._height)
Run Code Online (Sandbox Code Playgroud)

我想将其转换为 OpenCV 格式。我尝试将其转换为numpy.ndarray如此处所述但出现错误sip.voidptr object has an unknown size

有没有办法获得 numpy 数组(与cv2.VideoCapture read方法返回的格式相同)?

ing*_*var 6

我使用此代码获得了 numpy 数组:

channels_count = 4
pixmap = self._screen.grabWindow(0, self._x, self._y, self._width, self._height)
image = pixmap.toImage()
s = image.bits().asstring(self._width * self._height * channels_count)
arr = np.fromstring(s, dtype=np.uint8).reshape((self._height, self._width, channels_count)) 
Run Code Online (Sandbox Code Playgroud)


Ste*_*fan 6

可以通过执行以下操作来避免复制:

channels_count = 4
pixmap = self._screen.grabWindow(0, self._x, self._y, self._width, self._height)
image = pixmap.toImage()
b = image.bits()
# sip.voidptr must know size to support python buffer interface
b.setsize(self._height * self._width * channels_count)
arr = np.frombuffer(b, np.uint8).reshape((self._height, self._width, channels_count))
Run Code Online (Sandbox Code Playgroud)