0

lets assume we have a tensor representing an image of the shape (910, 270, 1) which assigned a number (some index) to each pixel with width=910 and height=270.

We also have a numpy array of size (N, 3) which maps a 3-tuple to an index.

I now want to create a new numpy array of shape (920, 270, 3) which has a 3-tuple based on the original tensor index and the mapping-3-tuple-numpy array. How do I do this assignment without for loops and other consuming iterations?

This would look simething like:

color_image = np.zeros((self._w, self._h, 3), dtype=np.int32)
self._colors = np.array(N,3) # this is already present
indexed_image = torch.tensor(920,270,1) # this is already present

#how do I assign it to this numpy array?
color_image[indexed_image.w, indexed_image.h] = self._colors[indexed_image.flatten()]
2
  • 1
    what is N? You can probably extend it to the size of the image for broadcasting Commented Sep 17, 2021 at 14:45
  • @Eumel N is is the count of indexes which are existent. This gets extended during runtime, as more and more indexes get mapped to a color. Commented Sep 17, 2021 at 14:50

1 Answer 1

1

Assuming you have _colors, and indexed_image. Something that ressembles to:

>>> indexed_image = torch.randint(0, 10, (920, 270, 1))
>>> _colors  = np.random.randint(0, 255, (N, 3))

A common way of converting a dense map to a RGB map is to loop over the label set:

>>> _colors = torch.FloatTensor(_colors)

>>> rgb = torch.zeros(indexed_image.shape[:-1] + (3,))
>>> for lbl in range(N):
...     rgb[lbl == indexed_image[...,0]] = _colors[lbl]
Sign up to request clarification or add additional context in comments.

3 Comments

That's amazing! So rgb[lbl == indexed_image[...,0]] is used as "if label is present in the indexed image" then assign a color?
Have a look at lbl == indexed_image[...,0]: it is a mask of the same shape as indexed_image containing 1s where the values of indexed_image are equal to label lbl. You can use this mask to index rgb and ultimately assign _colors[lbl] to only that selection.
Appreciate the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.