半透明区域的QPixmap转换为CVImage

发布时间 2023-09-10 23:01:12作者: Moneky
def pixmap_to_cv2(pixmap):
    # 将QPixmap转换为QImage
    image = pixmap.toImage()
    # 创建一个新的QImage,使用32位ARGB格式,以保留alpha通道信息
    image_with_alpha = QtGui.QImage(image.size(), QtGui.QImage.Format_ARGB32)
    image_with_alpha.fill(0)  # 将图像填充为完全透明
    # 将原始图像绘制到带有alpha通道的图像上
    painter = QtGui.QPainter(image_with_alpha)
    painter.drawImage(0, 0, image)
    painter.end()
    # 获取图像的像素数据
    image_data = image_with_alpha.bits().tobytes()
    # 将像素数据转换为numpy数组
    cv_image = np.ndarray(shape=(image_with_alpha.height(), image_with_alpha.width(), 4), dtype=np.uint8,
                          buffer=image_data)
    cv_image = cv2.cvtColor(cv_image,cv2.COLOR_BGR2RGBA)
    return cv_image