如何在Python中生成RGB立方体矩阵?
我想创建一个大小为256*256*3的标准化矩阵,这个矩阵用来表示RGB立方体,像这样:
我在opencv中尝试了以下代码(我导入了numpy作为np):
R = [np.true_divide(i, 256) for i in xrange(256)]
RGB_Cube = np.zeros((256, 256, 3), dtype=np.float64)
RGB_Cube[:, :, 0] = RGB_Cube[:, :, 1] = RGB_Cube[:, :, 2] = np.tile(R, (256,1))
然后我得到了这个结果:
我还尝试了这个(没有对通道进行标准化):
R = [i for i in xrange(256)]
# R = np.linspace(0, 1, 256, endpoint=True)
RGB_Cube = np.zeros((256, 256, 3), dtype=np.float64)
RGB_Cube[:, :, 0] = RGB_Cube[:, :, 1] = RGB_Cube[:, :, 2] = np.tile(R, (256,1))
但我得到了一个白色的图像。
我想把这个矩阵分成几个小立方体,然后找出这些小立方体的平均值。之后我会用这些信息来对给定的图像进行分割!
我不知道这个问题有多简单,我找不到解决办法。有人能帮忙吗?
谢谢
1 个回答
2
抱歉,我还是不太明白你需要什么。假设你想要一个“立方体”,用来表示所有可能的8位RGB值,那么你需要一个256 x 256 x 256的数组,而不是三个256 x 256的数组。
请注意,我真的觉得你不需要这样做。像这样的数据(包括子立方体)可以通过程序生成,而不需要把所有东西都存储在内存里。下面的代码存储了大约1600万个8位RGB值,保存到磁盘时大约占用140MB。
不过,代码在这里:
import pickle
import numpy as np
# full 8-bit RGB space
bits = 8
cube_dimension = 2**bits
full_rgb_space = np.ndarray((cube_dimension, cube_dimension, cube_dimension, 3),
dtype=np.uint8)
# this is really inefficient and will take a long time.
for i in range(cube_dimension):
print(i) # just to give some feedback while it's working
for j in range(cube_dimension):
for k in range(cube_dimension):
position = color = (i, j, k)
full_rgb_space[position] = color
# save it to see what you've got.
# this gives me a 140MB file.
with open('full_rgb_space.p', 'wb') as f:
pickle.dump(full_rgb_space, f)