Hadi
Hadi

Reputation: 5618

How to produce RGB cube matrix in python?

I tried to create a normalized matrix of size 256*256*3 which represent the RGB cube like this,

RGB Cube

I tried the following code in opencv-(I imported numpy as 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))

and I got this:

Output of the code

I also tried this(without normalizing the channels):

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))

but I got a white image.

I want to partition this matrix into sub-cuboids. Then finding the mean value of these cuboids. After that I will use this information for segmentation of a given image!

I don't know how much easy this problem is, I couldn't find a way to solve it. Can anyone help?

Thanks

Upvotes: 0

Views: 2629

Answers (1)

KobeJohn
KobeJohn

Reputation: 7545

Sorry I'm still not able to understand what you need yet. Assuming you want a "cube" that represents every possible 8-bit RGB value, you will need a 256 x 256 x 256 (x3) array. Not 3 256 x 256 (x3) arrays.

Please note - I really think you don't want to do this. The data for something like this (including sub-cubes) could be made procedurally without needing to store everything in memory. The code below stores all ~16 million values of 8-bit RGB space and takes about 140MB when pickled to disk.

Here it is anyway:

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)

Upvotes: 2

Related Questions