Path: blob/master/CharClassification/make_predictions.py
3118 views
import cv2 # for reading and writing or showing image1import numpy as np2import matplotlib.pyplot as plt3from keras.models import load_model4import keras5from keras.preprocessing import image6from keras.models import load_model7from net import Net8import sys910def load_image(img_path, show=False):11'''12Function: Convert image to tensor13Input: image_path (eg. /home/user/filename.jpg)14(Note prefer having absolute path)15show (default = False), set if you want to visualize the image16Return: tensor format of image17'''18# load image using image module19# convert to (32, 32) - if not already20img = image.load_img(img_path, target_size=(32, 32)) # Path of test image21# show the image if show=True22if show:23plt.imshow(img)24plt.axis('off')2526# converting image to a tensor27img_tensor = image.img_to_array(img) # (height, width, channels)28img_tensor = np.expand_dims(img_tensor, axis=0)29img_tensor /= 255.3031# return converted image32return img_tensor3334def predict(weights_path, image_path):35'''36Function: loads a trained model and predicts the class of given image37Input: weights_path (.h5 file, prefer adding absolute path)38image_path (image to predict, prefer adding absolute path)39Returns: none40'''41model = Net.build(32, 32, 3, weights_path)4243image = load_image(image_path, show=True) # load image, rescale to 0 to 144class_ = model.predict(image) # predict the output, returns 36 length array45print("Detected: ", class_[0]) # print what is predicted46output_indice = -1 # set it initially to -14748# get class index having maximum predicted score49for i in range(36):50if(i == 0):51max = class_[0][i]52output_indice = 053else:54if(class_[0][i] > max):55max = class_[0][i]56output_indice = i5758# append 26 characters (A to Z) to list characters59characters = []60for i in range(65, 65+26):61characters.append(chr(i))62# if output indice > 9 (means characters)63if(output_indice > 9):64final_result = characters[(output_indice - 9) - 1]65print("Predicted: ", final_result)66print("value: ", max) # print predicted score67# else it's a digit, print directly68else:69print("Predicted: ", output_indice)70print("value: ", max) # print it's predicted score717273if(len(sys.argv) < 2):74print("Enter test image path as an argument")75sys.exit(0)76test_image = sys.argv[1]7778predict("trained_weights.h5", test_image) # Specify weights file and Test image798081