从图像创建一维numpy数组

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

编辑:从我的评论中复制以便为问题提供更多背景信息

我忘记提及的一件事是我的最终目标是添加作为熊猫数据框的一列。我在尝试时遇到错误由于不止一个,将像素数组按原样放入数据帧尺寸。

我有一个32x32的图像,我想将其展平为一个1-D numpy数组,该数组表示在该像素处具有RGB值的对象。

img = Image.open(img_path)
pixels = np.asarray(img)
width, height = img.size
pixels = pixels.reshape(width * height, 3)

目前,这是我能做的最好的事情,同时又不会丢失一个对象中RGB值的分组。但是,通过这种实现,我得到了一个二维数组,每个元素都是这样的RGB值数组。

shape: (1024, 3)
[[255 255 255]
 [255 255 255]
 [255 255 255]
 ...
 [255 255 255]
 [255 255 255]
 [255 255 255]]

我希望我的数组的形状为(1024,1),并且每个元素都是RGB值的某个对象(可能是一个元组?)。谢谢。

python image numpy python-imaging-library numpy-ndarray
1个回答
0
投票

c.f。注释,数组作为数据框或一系列:

dataframe = pd.DataFrame(pixels)   # As a dataframe with one column per color channel
column = dataframe.apply(tuple, axis=1)  # As a Series of (r,g,b) tuples

然后,您可以根据需要将column用作另一个数据框的列

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