如何有效地将来自 X,Y,RGB_COLOR_INT pandas 数据帧的数据放入类似图像的 canvas numpy 数组中?

How to effectively put data from X,Y,RGB_COLOR_INT pandas dataframe into image-like canvas numpy array?

我有这样的 pandas 数据框:

x y color
0 826 1048 52416
1 583 1031 9745407
2 1873 558 6970623
3 1627 255 40618
4 49 1478 9745407
5 408 1863 14986239
6 111 1582 9745407
7 1334 1840 6970623
8 1908 1854 6970623

和 numpy 数组,其行为类似于图像 canvas,形状为 (width, height, 4),pandas X 和 Y 在 canvas 数组的宽度和高度范围内。

将 RGBA 整数值拆分到其各自的通道中,然后将它们放入 canvas(用 X、Y 表示)的有效方法是什么?


目前我可以像这样将 RGBA 与 numpy 分开:

np_data = dataframe.to_numpy(np.uint32)
rgb_channels = np_data[:, 2].view(np.uint8).reshape(np_data[:, 2].shape[0], 4)

但我无法通过 numpy 有效地应用这些值:

# This does not work
np.put(canvas, ((np_data[:, 0] * canvas.shape[0]) + (np_data[:, 1]), rgb_channels)
# I guess rgb_channels would have to have same size as canvas, as the index is applied to both (?) instead of the value argument being consumed for each index

唯一可行的方法是 python:

i = 0 # couldn't make enumerate or numpy.ndenumerate work properly
for x, y in np_data[:, [0, 1]]: # loop thru X,Y coordinates 
     canvas[x][y] = rgb_channels[i]

你的方法应该是这样的:

np_data = (df['color'].to_numpy()
             .astype('uint32')        # uint32
             .view('uint8')           # convert to uint8
             .reshape(len(df), -1)    # reshape 
          )

# new image
canvas = np.zeros((10,10,4), dtype='uint8')

# slicing
canvas[df['x'], df['y']] = np_data

我会像这样明确地解析频道

# use [3,2,1,0] if you are working with RGBA
powers = 256 ** np.array([2,1,0])

colors = (df.color.to_numpy()[:,None] & (powers*255))// powers

out = np.zeros((10,10,3), dtype='uint8')
out[df['x'], df['y']] = colors