0

I need to add a layer of normalization to the image in the preprocess.

It needs to be an additional layer to the model (and not seperate code in python), because I later transform the keras model to mlmodel.

This is the normalization I mean:

In python (from here):

parser.add_argument('--std', type=list, default=[0.229, 0.224, 0.225],
                                help='the std used to normalize your images')
parser.add_argument('--mean', type=list, default=[0.485, 0.456, 0.406],
                                help='the mean used to normalize your images')
        
normalize = transforms.Normalize(std=args.std, mean=args.mean)
        
transformation = transforms.Compose([transforms.ToTensor()])
        
            
man_normalize = transformation(man_resize)

In Android:

@Override
  | protected void addPixelValue(int pixelValue) {
  | imgData.putFloat((((pixelValue >> 16) & 0xFF)/255f - IMAGE_MEAN[0]) / IMAGE_STD[0]);
  | imgData.putFloat((((pixelValue >> 8) & 0xFF)/255f - IMAGE_MEAN[1]) / IMAGE_STD[1]);
  | imgData.putFloat(((pixelValue & 0xFF)/255f - IMAGE_MEAN[2]) / IMAGE_STD[2]);
  | }

I thought on Lambda layer, but I am not sure how to do it efficiently and per channel.

Thanks

jonb
  • 845
  • 1
  • 13
  • 36

1 Answers1

0

Solution with Lambda layer:

base_model = load_model(keras_model_p)

MEAN = [0.485, 0.456, 0.406]
STD = [0.229, 0.224, 0.225]
preprocess_layer = tf.keras.layers.Lambda(
    lambda x: (x - MEAN) / STD
)
model = Sequential()
model.add(tf.keras.Input(shape=(256, 192, 3))
model.add(preprocess_layer)
model.add(base_model)
jonb
  • 845
  • 1
  • 13
  • 36