Sorry for the late reply.
Yes, in my code snippet I’m using a randomly initialized mask, so you should use your mask.
I’m not aware of a fast built-in method to create this mapping, but I’m sure that my code is not the most efficient one. 
The line of code gets the indices for the current class index by comparing the target image to the current class mapping (color code).