Group work for a Monash Research Methods course
1import numpy as np
2from keras.models import Model, load_model
3from keras.utils import to_categorical
4import cv2
5from skimage import color, exposure
6from _cutter import image_cut
7
8def man_result_check():
9 pred_y = np.load("predicted_results.npy")
10 test_y = np.load("Waldo_test_lbl.npy")
11
12 test_y = to_categorical(test_y)
13
14 f = open("test_output.txt", 'w')
15 z = 0
16 for i in range(0, len(test_y)):
17 print(pred_y[i], test_y[i], file=f)
18 # Calculates correct predictions
19 if pred_y[i][0] == test_y[i][0]:
20 z+=1
21
22 print("Accuracy: {}%".format(z/len(test_y)*100))
23 f.close()
24
25'''
26Purpose:Loads a trained neural network model (using Keras) to classify an image
27Input: path/to/trained_model
28 image [or] path/to/image [if from_file=True]
29Returns:Boolean variable
30'''
31def is_Wally(trained_model_path, image, from_file=False):
32 if from_file:
33 img = cv2.imread(image) # Opens the image (in BGR format)
34
35 # Histogram normalization in v channel
36 hsv = color.rgb2hsv(img)
37 hsv[:, :, 2] = exposure.equalize_hist(hsv[:, :, 2])
38 img = color.hsv2rgb(hsv)
39
40 image = np.rollaxis(img, -1) # Rolls the colour axis to the front
41
42 trained_model = load_model(trained_model_path)
43 if trained_model.predict(image, verbose=1, batch_size=1)[0] == 1:
44 return 0
45 else:
46 return 1
47
48# Load fully puzzle image
49# Split image into array of images
50# use is_Wally(img) to classify image
51# Mark Wally image somehow (colour the border)
52# Stitch original image back together
53
54if __name__ == '__main__':
55 # Read image
56 image = cv2.imread("7.jpg")
57 # Split image
58 cuts = image_cut(image, 64, 64)
59 for i in range(len(cuts)):
60 # Transform block
61 hsv = color.rgb2hsv(cuts[i])
62 hsv[:, :, 2] = exposure.equalize_hist(hsv[:, :, 2])
63 block = color.hsv2rgb(hsv)
64 block = np.rollaxis(block, -1)
65 if is_Wally("Waldo.h5", block):
66 # Border block
67 GREEN = [0, 255, 0]
68 cuts[i] = cv2.copyMakeBorder(cuts[i][1:61,1:61],2,2,2,2,cv2.BORDER_CONSTANT,value=GREEN)
69
70 # Stitch image
71 width = int(image.shape[1]/64) # TODO: does not work if this is not actually an integer
72 i = 0
73 layers = []
74 while i < len(cuts):
75 filler = [ np.zeros((64,64,3)) for j in range(i+width - min(i+width, len(cuts))) ]
76 layers.append(np.concatenate(([cuts[j] for j in range(i, min(i+width, len(cuts)))] + filler),axis=1))
77 i = i + width
78 image = np.concatenate(layers, axis=0)
79 # Show image
80 cv2.imwrite('output.png',image)