【问题标题】:Convert PyQt5 QPixmap to numpy ndarray将 PyQt5 QPixmap 转换为 numpy ndarray
【发布时间】:2017-12-14 16:43:55
【问题描述】:

我有像素图:

pixmap = self._screen.grabWindow(0,
                                 self._x, self._y,
                                 self._width, self._height)

我想把它转换成 OpenCV 格式。 我尝试按照here 的描述将其转换为numpy.ndarray,但出现错误sip.voidptr object has an unknown size

有没有办法获取numpy数组(与cv2.VideoCaptureread方法返回格式相同)?

【问题讨论】:

  • 什么是_screen?
  • QtWidgets.QApplication.primaryScreen()
  • 你在使用qt_image_to_array函数吗?
  • 是的。但没有成功。我不确定它是否适用于我的情况
  • 您是否验证了 QPixmap 是有效的,您是否尝试过显示或保存到文件中?

标签: python numpy pyqt pyqt5 qpixmap


【解决方案1】:

我使用这段代码得到了 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)) 

【讨论】:

  • 这确实对我有用,谢谢,但是,它会引发 DeprecationWarning。因此,建议将最后一行代码中的 np.fromstring 替换为 np.frombuffer。
【解决方案2】:

可以通过以下方式避免复制:

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))

【讨论】:

    【解决方案3】:

    这是一个函数:

    def QPixmapToArray(pixmap):
        ## Get the size of the current pixmap
        size = pixmap.size()
        h = size.width()
        w = size.height()
    
        ## Get the QImage Item and convert it to a byte string
        qimg = pixmap.toImage()
        byte_str = qimg.bits().tobytes()
    
        ## Using the np.frombuffer function to convert the byte string into an np array
        img = np.frombuffer(byte_str, dtype=np.uint8).reshape((w,h,4))
    
        return img
    

    【讨论】:

    • 考虑添加关于您的解决方案的解释,只有代码答案可能对某些人有帮助,但不是对所有人都有帮助
    • 对答案的评论。
    • 这给了我AttributeError: 'sip.voidptr' object has no attribute 'tobytes'。框架有什么变化吗?
    • @MarkCh sip.voidptr 表示您的 QImg 很可能是空的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多