image_classifier.py 953 B

1234567891011121314151617181920212223242526272829303132
  1. from tensorflow.keras.applications import InceptionV3
  2. from tensorflow.keras.applications.inception_v3 import preprocess_input, decode_predictions
  3. from tensorflow.keras.preprocessing import image
  4. import numpy as np
  5. IMG_SIZE = 299
  6. PREDICTION_MODEL = InceptionV3(weights='imagenet')
  7. def classify_image(image_path: str):
  8. img_path = f'./app/{image_path}'
  9. img = image.load_img(img_path, target_size=(IMG_SIZE, IMG_SIZE))
  10. x = image.img_to_array(img)
  11. x = np.expand_dims(x, axis=0)
  12. x = preprocess_input(x)
  13. preds = PREDICTION_MODEL.predict(x)
  14. result = decode_predictions(preds, top=3)[0]
  15. payload = []
  16. for _, value, _ in result:
  17. payload.append(value)
  18. return payload
  19. def warm_up():
  20. img_path = f'./app/test.png'
  21. img = image.load_img(img_path, target_size=(IMG_SIZE, IMG_SIZE))
  22. x = image.img_to_array(img)
  23. x = np.expand_dims(x, axis=0)
  24. x = preprocess_input(x)
  25. PREDICTION_MODEL.predict(x)