keras-io/CutMix_Data_Augmentation_for_Image_Classification
1
1import numpy as np2import tensorflow as tf3import gradio as gr4from huggingface_hub import from_pretrained_keras5import cv26# import matplotlib.pyplot as plt7 8 9model = from_pretrained_keras("keras-io/CutMix_data_augmentation_for_image_classification")10 11# functions for inference 12IMG_SIZE = 3213 14class_names = [15 "Airplane",16 "Automobile",17 "Bird",18 "Cat",19 "Deer",20 "Dog",21 "Frog",22 "Horse",23 "Ship",24 "Truck",25]26 27# resize the image and it to a float between 0,128def preprocess_image(image, label):29 image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))30 image = tf.image.convert_image_dtype(image, tf.float32) / 255.031 return image, label32 33 34def read_image(image):35 image = tf.convert_to_tensor(image)36 image.set_shape([None, None, 3])37 print('$$$$$$$$$$$$$$$$$$$$$ in read image $$$$$$$$$$$$$$$$$$$$$$')38 print(image.shape)39# plt.imshow(image)40# plt.show()41 # image = tf.image.resize(images=image, size=[IMG_SIZE, IMG_SIZE])42 # image = image / 127.5 - 143 image, _ = preprocess_image(image, 1) # 1 here is a temporary label44 return image45 46def infer(input_image):47 print('#$$$$$$$$$$$$$$$$$$$$$$$$$ IN INFER $$$$$$$$$$$$$$$$$$$$$$$')48 image_tensor = read_image(input_image)49 print(image_tensor.shape)50 predictions = model.predict(np.expand_dims((image_tensor), axis=0))51 predictions = np.squeeze(predictions)52 predictions = np.argmax(predictions) # , axis=253 predicted_label = class_names[predictions.item()]54 return str(predicted_label)55 56 57# get the inputs58input = gr.inputs.Image(shape=(IMG_SIZE, IMG_SIZE))59# the app outputs two segmented images60output = [gr.outputs.Label()]61# it's good practice to pass examples, description and a title to guide users62examples = [["./content/examples/Frog.jpg"], ["./content/examples/Truck.jpg"]] 63title = "Image classification"64description = "Upload an image or select from examples to classify it. The allowed classes are - Airplane, Automobile, Bird, Cat, Deer, Dog, Frog, Horse, Ship, Truck <p><b>Space author: Harshavardhan</b> <br><b> Keras example author: <a href=\"https://twitter.com/sayannath2350\"> Sayan Nath </a> </b> <br> <a href=\"https://keras.io/examples/vision/cutmix/\">link to the original Keras example</a> </p>"65 66gr_interface = gr.Interface(infer, input, output, examples=examples, allow_flagging=False, analytics_enabled=False, title=title, description=description).launch(enable_queue=True, debug=False)67gr_interface.launch()68 69 70 71 72 