12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- # D:/workplace/python
- # -*- coding: utf-8 -*-
- # @File :test.py
- # @Author:Guido LuXiaohao
- # @Date :2020/4/8
- # @Software:PyCharm
- import cv2
- import time
- import os
- import numpy as np
- import tensorflow as tf
- from keras.preprocessing.image import img_to_array
- from keras.models import load_model
- from keras.backend.tensorflow_backend import set_session
- os.environ["CUDA_VISIBLE_DEVICES"] = "0" # 指定GPU
- config = tf.ConfigProto()
- config.gpu_options.allow_growth = True # 按需
- set_session(tf.Session(config=config))
- def predict(image_path, model_path, norm_size=128):
- # load the trained convolutional neural network
- print("[INFO] loading network...")
- model = load_model(model_path)
- # load the image
- image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), -1)
- # pre-process the image for classification
- image = cv2.resize(image, (norm_size, norm_size))
- image = image.astype("float") / 255.0
- image = img_to_array(image)
- image = np.expand_dims(image, axis=0)
- # classify the input image
- result = model.predict(image)[0]
- proba = np.max(result)
- label = str(np.where(result == proba)[0])
- label = "{}: {:.2f}%".format(label, proba * 100)
- print(label)
- def resize_LongestMaxSize(image, norm_size):
- image_height = image.shape[0]
- image_width = image.shape[1]
- if image_height > image_width:
- image = cv2.resize(image, (int(norm_size * image_width / image_height), norm_size))
- pad_len = int((norm_size - norm_size * image_width / image_height) / 2)
- image = np.pad(image, ((0, 0), (pad_len, pad_len), (0, 0)), constant_values=0)
- image = cv2.resize(image, (norm_size, norm_size))
- else:
- image = cv2.resize(image, (norm_size, int(norm_size * image_height / image_width)))
- pad_len = int((norm_size - norm_size * image_height / image_width) / 2)
- print(pad_len)
- image = np.pad(image, ((pad_len, pad_len), (0, 0), (0, 0)), constant_values=0)
- image = cv2.resize(image, (norm_size, norm_size))
- return image
|