从Matplotlib贴图中提取RGBA

2024-10-03 11:22:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将使用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不能读取它,但我不知道如何使它正常工作。想法

先谢谢你


Tags: toimagematplotlibpltcv2opencvsplitvalues
1条回答
网友
1楼 · 发布于 2024-10-03 11:22:53

我认为你应该做的是改变电话,使你的形象

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%确定这是你想要的。但我相信它应该管用

相关问题 更多 >