title: Mapping RGB values in an image to a corresponding ID using a dictionary
body: <p>I am working on a segmentation problem where given an image, each RGB value corresponds to a class label. The problem I have is to efficiently map RGB values from an image (numpy array) to a corresponding class label image.</p>
  
  <p>Let's provide the following simplified example:</p>
  
  <pre><code>color2IdMap 
  {(100,0,100):0, (0,200,0):2}
  
  labelOld 
  array([[[100,0,100],
           [0,200,0]],
         [[100,0,100],
          [0,200,0]]], dtype=uint8)
  </code></pre>
  
  <p>(in a real example the colorIdMap will have about 20 entries and labelOld will be an array of shape: (1024,512,3))</p>
  
  <p>Now I want the result to be the following mapped array. with shape: (1024,512)</p>
  
  <pre><code>labelNew
  array([[ 0, 2],
         [ 0, 2]])
  </code></pre>
  
  <p>I attempted to do this with loops and list comprehensions but both methods are quite slow (about ~10seconds per image, which is a big number for 250K images). And I am wondering if there is a faster way of doing it.</p>
  
  <hr>
  
  <p><strong>Attempted method 1:</strong></p>
  
  <pre><code>labelNew = np.empty((1052,1914), dtype=np.uint8)
  for i in range(1052):
      for j in range(1914):
          labelNew[i, j] = color2IdMap[tuple(labelOld[i, j])]
  </code></pre>
  
  <p><strong>Attempted method 2:</strong></p>
  
  <pre><code>labelNew = [[color2IdMap[tuple(x)] for x in y] for y in labelOld]
  </code></pre>
  
  <hr>
  
  <p>So, my question is if there is any faster and more efficient way of doing this?</p>