mardi 18 septembre 2018

Python if-elif-else runtime optimization

I did a search on the previous asked question, but without finding what i need to optimize my code.

For info, I am running on Python 2.7 but could change to 3 if needed

I am converting every pixel of an image and because of some condition i have to do it pixel by pixel. So i have nested for loop with an if-elif-else statement inside, and it takes an awful long time to run. For an image of 1536 x 2640, the whole code takes ~20 seconds and 90% of time is inside this double for loop

I believe there should be a better way to write the below code

  for pixel in range(width):
    for row in range(height):
      ADC = img_original[row, pixel]
      if ADC < 84:
        gain   = gain1
        offset = offset1
      elif ADC > 153: 
        gain   = gain3
        offset = offset3
      else:
        gain   = gain2
        offset = offset2

      Conv_ADC  = int(min(max(ADC * gain + offset, 0),255))
      img_conv[row, pixel] = Conv_ADC

Thanks for the help

Aucun commentaire:

Enregistrer un commentaire