Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/CharClassification/make_predictions.py
3118 views
1
import cv2 # for reading and writing or showing image
2
import numpy as np
3
import matplotlib.pyplot as plt
4
from keras.models import load_model
5
import keras
6
from keras.preprocessing import image
7
from keras.models import load_model
8
from net import Net
9
import sys
10
11
def load_image(img_path, show=False):
12
'''
13
Function: Convert image to tensor
14
Input: image_path (eg. /home/user/filename.jpg)
15
(Note prefer having absolute path)
16
show (default = False), set if you want to visualize the image
17
Return: tensor format of image
18
'''
19
# load image using image module
20
# convert to (32, 32) - if not already
21
img = image.load_img(img_path, target_size=(32, 32)) # Path of test image
22
# show the image if show=True
23
if show:
24
plt.imshow(img)
25
plt.axis('off')
26
27
# converting image to a tensor
28
img_tensor = image.img_to_array(img) # (height, width, channels)
29
img_tensor = np.expand_dims(img_tensor, axis=0)
30
img_tensor /= 255.
31
32
# return converted image
33
return img_tensor
34
35
def predict(weights_path, image_path):
36
'''
37
Function: loads a trained model and predicts the class of given image
38
Input: weights_path (.h5 file, prefer adding absolute path)
39
image_path (image to predict, prefer adding absolute path)
40
Returns: none
41
'''
42
model = Net.build(32, 32, 3, weights_path)
43
44
image = load_image(image_path, show=True) # load image, rescale to 0 to 1
45
class_ = model.predict(image) # predict the output, returns 36 length array
46
print("Detected: ", class_[0]) # print what is predicted
47
output_indice = -1 # set it initially to -1
48
49
# get class index having maximum predicted score
50
for i in range(36):
51
if(i == 0):
52
max = class_[0][i]
53
output_indice = 0
54
else:
55
if(class_[0][i] > max):
56
max = class_[0][i]
57
output_indice = i
58
59
# append 26 characters (A to Z) to list characters
60
characters = []
61
for i in range(65, 65+26):
62
characters.append(chr(i))
63
# if output indice > 9 (means characters)
64
if(output_indice > 9):
65
final_result = characters[(output_indice - 9) - 1]
66
print("Predicted: ", final_result)
67
print("value: ", max) # print predicted score
68
# else it's a digit, print directly
69
else:
70
print("Predicted: ", output_indice)
71
print("value: ", max) # print it's predicted score
72
73
74
if(len(sys.argv) < 2):
75
print("Enter test image path as an argument")
76
sys.exit(0)
77
test_image = sys.argv[1]
78
79
predict("trained_weights.h5", test_image) # Specify weights file and Test image
80
81