test.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # D:/workplace/python
  2. # -*- coding: utf-8 -*-
  3. # @File :test.py
  4. # @Author:Guido LuXiaohao
  5. # @Date :2020/4/8
  6. # @Software:PyCharm
  7. import cv2
  8. import time
  9. import os
  10. import numpy as np
  11. import tensorflow as tf
  12. from keras.preprocessing.image import img_to_array
  13. from keras.models import load_model
  14. from keras.backend.tensorflow_backend import set_session
  15. os.environ["CUDA_VISIBLE_DEVICES"] = "0" # 指定GPU
  16. config = tf.ConfigProto()
  17. config.gpu_options.allow_growth = True # 按需
  18. set_session(tf.Session(config=config))
  19. def predict(image_path, model_path, norm_size=128):
  20. # load the trained convolutional neural network
  21. print("[INFO] loading network...")
  22. model = load_model(model_path)
  23. # load the image
  24. image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), -1)
  25. # pre-process the image for classification
  26. image = cv2.resize(image, (norm_size, norm_size))
  27. image = image.astype("float") / 255.0
  28. image = img_to_array(image)
  29. image = np.expand_dims(image, axis=0)
  30. # classify the input image
  31. result = model.predict(image)[0]
  32. proba = np.max(result)
  33. label = str(np.where(result == proba)[0])
  34. label = "{}: {:.2f}%".format(label, proba * 100)
  35. print(label)
  36. def resize_LongestMaxSize(image, norm_size):
  37. image_height = image.shape[0]
  38. image_width = image.shape[1]
  39. if image_height > image_width:
  40. image = cv2.resize(image, (int(norm_size * image_width / image_height), norm_size))
  41. pad_len = int((norm_size - norm_size * image_width / image_height) / 2)
  42. image = np.pad(image, ((0, 0), (pad_len, pad_len), (0, 0)), constant_values=0)
  43. image = cv2.resize(image, (norm_size, norm_size))
  44. else:
  45. image = cv2.resize(image, (norm_size, int(norm_size * image_height / image_width)))
  46. pad_len = int((norm_size - norm_size * image_height / image_width) / 2)
  47. print(pad_len)
  48. image = np.pad(image, ((pad_len, pad_len), (0, 0), (0, 0)), constant_values=0)
  49. image = cv2.resize(image, (norm_size, norm_size))
  50. return image