image_classifier.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  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. from PIL import Image
  6. import cv2
  7. IMG_SIZE = 299
  8. PREDICTION_MODEL = InceptionV3(weights='imagenet')
  9. def classify_image(image_path: str):
  10. img_path = f'./app/{image_path}'
  11. # img = image.load_img(img_path, target_size=(IMG_SIZE, IMG_SIZE))
  12. target_image = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
  13. resized_target_image = cv2.resize(target_image, (IMG_SIZE, IMG_SIZE))
  14. x = image.img_to_array(resized_target_image)
  15. x = np.expand_dims(x, axis=0)
  16. x = preprocess_input(x)
  17. preds = PREDICTION_MODEL.predict(x)
  18. result = decode_predictions(preds, top=3)[0]
  19. payload = []
  20. for _, value, _ in result:
  21. payload.append(value)
  22. return payload
  23. def warm_up():
  24. img_path = f'./app/test.png'
  25. img = image.load_img(img_path, target_size=(IMG_SIZE, IMG_SIZE))
  26. x = image.img_to_array(img)
  27. x = np.expand_dims(x, axis=0)
  28. x = preprocess_input(x)
  29. PREDICTION_MODEL.predict(x)