0

I have a large RGB image, I want to convert each RGB value to an index_id based on a map. I am doing that as following but it is very slow. is there a faster way to do it?

NewDic = OrderedDict([
            ((0,0,0), 0),
            ((20,20,20), 1),
            ((100,20,3),2) ])


ann = Image.open(img_rgb)
ann = np.asarray(ann)
zeroann = np.zeros((ann.shape[0],ann.shape[1]))

for x in range(ann.shape[0]):
  for y in range(ann.shape[1]):  
     A = ann[x,y,:]
     zeroann[x,y] = NewDic[tuple(A)]
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Albert
  • 184
  • 3
  • 3
  • 14
  • 1
    Loops are slow in Python; try to vectorize this. Do all your RGB values appear in the dictionary, or do you need to find the nearest dictionary value? – Cris Luengo Mar 06 '20 at 16:07
  • I think you want to quantize to a known palette... https://stackoverflow.com/a/57202093/2836621 – Mark Setchell Mar 06 '20 at 16:22

1 Answers1

0

Do you need a specific mapping otherwise you could try a direct mapping.

ann = Image.open(img_rgb)
ann = np.asarray(ann)
# define newann as:
newoann = ann[:, :, 0] + ann[:, :, 1] * 256 + ann[:, :, 2] * 256**2
# Then do the mapping

This will lead to a unique index for every RGB Value.

Albert
  • 184
  • 3
  • 3
  • 14
pask
  • 899
  • 9
  • 19
  • 1
    Every RGB Value is equivalent to a number given in base 256. This will just convert the base 256 number to decimal. – pask Mar 08 '20 at 07:47