从 Matplotlib 地图中提取 RGBA

Extract RGBA from Matplotlib maps

我正在尝试将使用 Matplotlib imshow 创建的图形转换为 RGBA 值,但出现以下错误:

ValueError: not enough values to unpack (expected 4, got 0)

这是我的代码:

speed0 = speed[0, :, :].values   

figsize = (7, 7)
cbarkw = dict(shrink=0.6, extend='both')

fig, ax = plt.subplots(figsize=figsize)
i = plt.imshow(speed0, origin='lower')
cbar = plt.colorbar(i, **cbarkw)
plt.axis('off')

def matplotlib_to_opencv(i):
    image = i._rgbacache
    r, g, b, a = cv2.split(image)
    return np.flipud(cv2.merge([b, g, r, a]))

image = matplotlib_to_opencv(i)

其中 speed0 是 (192x111) 的风数据集。我认为 'image' 是空缓存,因此 cv2.split 无法读取它,但我不知道如何使其正常工作。想法?

提前谢谢你。

我认为您应该做的是将调用更改为 make_image

import numpy as np
import matplotlib.pyplot as plt
import cv2

speed = np.random.random((4, 192, 111))

speed0 = speed[0, :, :]

figsize = (7, 7)
cbarkw = dict(shrink=0.6, extend='both')

fig, ax = plt.subplots(figsize=figsize)
im = plt.imshow(speed0, origin='lower')

cbar = plt.colorbar(im, **cbarkw)
plt.axis('off')


def matplotlib_to_opencv(im):
    image = im.make_image('TkAgg')
    # this returns
    #         -------
    #         image : (M, N, 4) uint8 array
    #             The RGBA image, resampled unless *unsampled* is True.
    #         x, y : float
    #             The upper left corner where the image should be drawn, in pixel
    #             space.
    #         trans : Affine2D
    #             The affine transformation from image to pixel space.
    #         """
    # So you just want the first 
    r, g, b, a = cv2.split(image[0])
    return np.flipud(cv2.merge([b, g, r, a]))

image = matplotlib_to_opencv(im)


plt.show()

因为我没有你的数据集,所以我不能 100% 确定这就是你想要的。但我相信它应该有效。