在 pd 数据框中转换为 2d 数组后,3d 数组图像缺少蓝色值

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

我正在尝试编写一个Python代码,将3d数组图像转换为格式为“RGB(r,g,b)”的2d数组并将它们插入到pd数据帧中,一切正常,我有一个很多缺失的蓝色值有人知道为什么以及如何修复它们吗?

这是代码

image = io.imread('px.jpg')

# Convert the 3D array to a 2D array of RGB strings
rgb_strings_array = np.apply_along_axis(lambda row: f"RGB({int(row[0])}, {int(row[1])}, {int(row[2])})", axis=2, arr=image)

# Create a DataFrame with the RGB strings array
df = pd.DataFrame(rgb_strings_array, columns=range(rgb_strings_array.shape[1]))

输出是enter image description here,实际上是所需的项目,缺少值就是问题

python pandas numpy matplotlib data-science
1个回答
0
投票

问题是

np.apply_along_axis
正在生成一个
dtype="<U12"
数组,即 12 个字符的 unicode。问题是有些 RGB 字符串比这个长,所以它们被切断了。实际上,您不应该使用 numpy 来处理字符串。解析可以轻松地在本机 Python 中完成,并且结果仍然可以转换为 pandas DataFrame。

import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
image = rng.integers(0, 255, size=(4,4,3))

rbg_strings_array = [[f"RGB({int(val[0])}, {int(val[1])}, {int(val[2])})"
                      for val in row]
                     for row in image]
df = pd.DataFrame(rbg_strings_array, columns=range(len(rbg_strings_array)))
print(df)

结果:

0 1 2 3
0 RGB(22, 197, 166) RGB(111, 110, 218) RGB(21, 177, 51)
1 RGB(187, 194, 182) RGB(200, 130, 32) RGB(214, 114, 127)
2 RGB(199, 164, 102) RGB(209, 139, 113) RGB(114,57,23)
3 RGB(218, 211, 70) RGB(161, 42, 193) RGB(178,90,17)
© www.soinside.com 2019 - 2024. All rights reserved.