如何在Python中将图像数组转换为2D数组

问题描述 投票:1回答:3

我有一个形状的numpy数组:

(50000, 32, 32, 3)
  • 50000是图像的数量
  • 32, 32是高度和宽度
  • 3是具有0-1范围的RGB值

我想将其转换为2D形状:

(50000, 1024)

在这里,我将在一行中显示50000个图像,RGB值将被转换为让我们说十六进制值我已经经历了很多转换过程到堆栈溢出并且我找到了一些。我知道如果我的数组是一个已经转换过的值的3D数组,我可以很容易地使用reshape()function将其转换为2D。现在我正在搜索的是转换RGB值和重塑数组的最简单方法

这可能是1或2行还是我应该使用外部函数?

python arrays rgb reshape
3个回答
2
投票

首先使用您喜欢的任何函数将最后一维中的RGB值转换为HEX值。这SO answer可能有所帮助。

然后重塑然后适用于任意数量的维度:

import numpy as np

def rgb2hex(r, g, b):
    return '#%02x%02x%02x' % (r, g, b)

vfunc = np.vectorize(rgb2hex)

a = (np.random.uniform(0,1,(10,5,5,3))*255).astype(int)

c = vfunc(a[:,:,:,0], a[:,:,:,1], a[:,:,:,2])

c.reshape((10,25))

1
投票

为了做到这一点,你首先需要重塑ndarraynp.reshape):

a = np.random.randint(1,10,(500, 32, 32, 3))
a_r = np.reshape(a, (500, 1024, 3))
print(a_r.shape)
# (500, 1024, 3)

现在,为了将RGB值沿着最后一个维度转换为十六进制表示,您可以定义一个函数,该函数使用简单的字符串格式返回三个值的十六进制表示:

def rgb_to_hex(x):
    return '#{:02X}{:02X}{:02X}'.format(*rgb.reshape(3))

要沿最后一个轴的所有行应用转换,您可以使用np.apply_along_axis

a_new = np.apply_along_axis(rgb2hex, axis=-1, arr=a_r).shape
print(a_new.shape)
# (500, 1024)

1
投票

以下将RGB值组合为单个值

x=np.zeros((100,32,32,3))
x[:,:,:,0] = np.trunc(x[:,:,:,0]) + np.trunc(x[:,:,:,1] *256) + np.trunc(x[:,:,:,2] *65535)
y=x[:,:,:,0]
print(y.shape)

由此产生的y形状:(100,32,32)

接下来,您可以在y上使用reshape函数。

© www.soinside.com 2019 - 2024. All rights reserved.