从Matplotlib地图中提取RGBA

时间:2019-10-04 09:14:34

标签: python opencv rgba

我正在尝试将用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)的风力数据集。我认为“图像”是一个空缓存,因此cv2.split无法读取它,但我不知道如何使其正常工作。想法?

谢谢。

1 个答案:

答案 0 :(得分:1)

我认为您应该做的就是将调用更改为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%地确定这就是您想要的。但是我相信它应该起作用。