python - 将 QPixmap 转换为 Numpy

标签 python numpy pyqt4

要将 numpy 矩阵转换为 QPixmap,我使用此函数:

def np2qpixmap(np_img):
    frame = cv2.cvtColor(np_img, cv2.COLOR_BGR2RGB)
    img = QtGui.QImage(frame, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888)
    return QtGui.QPixmap.fromImage(img)

现在如何进行逆运算?

最佳答案

这是我不久前为一些爱好项目编写的函数...

import copy
import numpy as np

def qt_image_to_array(img, share_memory=False):
    """ Creates a numpy array from a QImage.

        If share_memory is True, the numpy array and the QImage is shared.
        Be careful: make sure the numpy array is destroyed before the image, 
        otherwise the array will point to unreserved memory!!
    """
    assert isinstance(img, QtGui.QImage), "img must be a QtGui.QImage object" 
    assert img.format() == QtGui.QImage.Format.Format_RGB32, \
        "img format must be QImage.Format.Format_RGB32, got: {}".format(img.format())

    img_size = img.size()
    buffer = img.constBits()

    # Sanity check
    n_bits_buffer = len(buffer) * 8
    n_bits_image  = img_size.width() * img_size.height() * img.depth()
    assert n_bits_buffer == n_bits_image, \
        "size mismatch: {} != {}".format(n_bits_buffer, n_bits_image) 

    assert img.depth() == 32, "unexpected image depth: {}".format(img.depth())

    # Note the different width height parameter order!
    arr = np.ndarray(shape  = (img_size.height(), img_size.width(), img.depth()//8),
                     buffer = buffer, 
                     dtype  = np.uint8)

    if share_memory:
        return arr
    else:
        return copy.deepcopy(arr)

关于python - 将 QPixmap 转换为 Numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37552924/

相关文章:

python - 创建列表列表。修改列表中的元素

python - 为什么 json python 程序总是出现错误

Python正则表达式,分割参数,忽略引号中的逗号

python - 如何使用numpy从2D图像矩阵生成所有(x,y,像素值)元组的列表?

python - PyQt4 和 Python 3 - 显示来自 URL 的图像

python - __builtin__ 和 __builtins__ 有什么区别?

python - 以不同方式切片 numpy 数组的不同行

python - NumPy 对于涉及数组各个元素的算法的性能

python - TypeError : PyQt4. QtCore.QVariantAnimation 表示 C++ 抽象类,无法实例化

python - 将隐藏数据插入组合框pyqt