adrienlucca.net
adrienlucca.net

Reputation: 687

Numpy create an index of values in an array and replace values by others

I have two sets of values RGB and XYZ in np.arrays that have the same length. The values in RGB and XYZ correspond to the same values in two different color spaces, the order of their appearance in the vectors is the same.

I have another array RGB_picture that contains values similar to the ones listed in RGB.

I want to find a way to replace the RGB values in RGB_picture by the corresponding XYZ values in a new array XYZ_picture.

example:

RGB = np.array([[0,0,0], [0,0,1], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,1]])

XYZ = np.array([[0.237,0.32,0.8642], [0.43234,0.34,1], [0.2432,.31,0.324], [0.3242,1.324,1.234], [1.32,0.4,0.23], [1.432,0.32423,1.342], [1.234,1.324,1.324324]])

#6 pixels image
RGB_image = np.array([[[0,0,1],[0,0,1],[0,0,1],
                       [0,1,1],[1,0,0],[1,0,1]]])

"""I want to return this"""

>print XYZ_image 

>[[0.43234,0.34,1],[0.43234,0.34,1],[0.43234,0.34,1]],

>[0.3242,1.324,1.234], [1.32,0.4,0.23], [1.432,0.32423,1.342]]

I tried to do it with numpy but couldn't find how, would you help a bit?

Here's what I have but it is no numpy solution, so it is very slow:

XYZ_image = np.zeros_like(RGB_image)

w, h = RGB_image.shape

for i in xrange(w):
    for j in xrange(h):
        pixel = RGB_image[i,j]

        for k in xrange(len(RGB)):

            rgb = RGB[k]

            if rgb == pixel:

                XYZ_image[i,j] = XYZ[k]
                break

Upvotes: 0

Views: 317

Answers (1)

AQiccl135
AQiccl135

Reputation: 33

It sounds like you are trying to use the RGB values as indexes. You can solve this with regular Python. Make a dict of

my_dict = {RGB_value_1: XYZ_Value_1, RGB_value_2: XYZ_Value_2, etc}

then for every value in RGB_picture

my_dict[RGB_picture_value]

EDIT: Using your code

my_dict = {RGB[i]: XYZ[i] for i in range(len(RGB))}
return [my_dict[x] for x in RGB_image]

Please note that for this to work, RGB, and RGB_picture values need to be immutable (like tuples)

Upvotes: 1

Related Questions