-
Notifications
You must be signed in to change notification settings - Fork 0
/
hopfield.py
66 lines (47 loc) · 1.42 KB
/
hopfield.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
Example of use Hopfield Recurrent network
=========================================
Task: Recognition of Simpsons
"""
import cv2, glob
import numpy as np
import neurolab as nl
import matplotlib.pyplot as plt
IMAGE_SIZE = (48, 48, 3) #size 48x48 pixels
TEST_PATH = './data/test/*.png'
TRAIN_PATH = './data/train/*.png'
def img2array(name):
img = cv2.imread(name) #read binary image
img = img.flatten() #Return a copy of the array collapsed into one dimension.
img[img == 255] = 1
return img
def array2img(array):
array[array == -1] = 0
array *= 255 # assing white spaces
img = np.reshape(array,IMAGE_SIZE) #transform one dimension array to multidimension array
return img
def array2float(array):
tmp = np.asfarray(array)
tmp[tmp == 0] = -1
return tmp
def show_images(images):
fig = plt.figure()
ax = fig.add_subplot(1, 2, 1)
imgplot = plt.imshow(images[0])
ax.set_title('Test')
ax = fig.add_subplot(1, 2, 2)
imgplot = plt.imshow(images[1])
ax.set_title('Result')
plt.show()
target = []
for file in glob.glob(TRAIN_PATH):
array = img2array(file)
target.append(array)
target = array2float(target)
net = nl.net.newhop(target) # Create and train network
img_test = img2array('./data/test/lisa1.png')
test = array2float(img_test)
out = net.sim([test]) #test network
out_image = array2img(out[0]) #output network image
img_test = array2img(test) #test image
show_images([img_test, out_image])