-
Notifications
You must be signed in to change notification settings - Fork 0
/
Image2vector.py
193 lines (140 loc) · 4.84 KB
/
Image2vector.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import coco
from cache import cache
import os, time, re, math
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from spacy.lang.en import English
nlp = English()
stopword = 'stopwords_en.txt'
dir_path = 'data\coco'
def set_path_stopword(newpath):
global stopword
stopword = os.path.join(newpath, stopword)
def set_dir_path(newpath):
global dir_path
coco.set_data_dir(newpath)
dir_path = newpath
def remove_stopwords(words, stopwords):
cleaned_text = [w.lower() for w in words if w not in stopwords]
return cleaned_text
def load_image(path, size=None):
"""
Load the image from the given file-path and resize it
to the given size if not None.
"""
# Load the image using PIL.
img = Image.open(path)
# Resize image if desired.
if not size is None:
img = img.resize(size=size, resample=Image.LANCZOS)
# Convert image to numpy array.
img = np.array(img)
# Scale image-pixels so they fall between 0.0 and 1.0
img = img / 255.0
# Convert 2-dim gray-scale array to 3-dim RGB array.
if (len(img.shape) == 2):
img = np.repeat(img[:, :, np.newaxis], 3, axis=2)
return img
def show_image(idx, filenames_val, captions_val, cap=True):
dir = coco.val_dir
filename = filenames_val[idx]
captions = captions_val[idx]
# Path for the image-file.
path = os.path.join(dir, filename)
# Print the captions for this image.
if cap:
for caption in captions:
print(caption)
# Load the image and plot it.
img = load_image(path)
plt.imshow(img)
plt.show()
def lemma_spacy(str_input):
doc = nlp(str_input.lower())
lemma =' '.join(i.lemma_ for i in doc)
return re.sub( "[^\w]", " ",lemma).split()
def _Image2data(captions, stopwords):
data = dict()
voc = []
for caption in captions:
#listCap = remove_stopwords(re.sub( "[^\w]", " ",caption).split(),stopwords)
listCap = remove_stopwords(lemma_spacy(caption),stopwords)
voc.extend(listCap)
for word in listCap:
t = data.get(word)
if t == None:
data[word] = 1
else: data[word] = t+1
return data, voc
def _load_vector(filenames, captions):
# load filename and caption from dir val
# file stopword_en
f = open(stopword, 'r')
stopwords = [line.strip() for line in f.readlines()]
f.close()
# collect data, vocabulary of each file
data = dict()
voc = []
number_files = len(filenames)
for i in range(number_files):
data[i], temp = _Image2data(captions[i], stopwords)
voc.extend(temp)
voc = sorted(list(set(voc)))
number_voc = len(voc)
BoW = np.zeros((number_voc, number_files), dtype=np.int)
invert = [[] for _ in range(number_voc)]
for i in range(number_voc):
for j in range(number_files):
freq = data[j].get(voc[i],0)
if freq != 0:
BoW[i][j] = freq
invert[i].append(j)
Vector = [(BoW[i], voc[i], invert[i]) for i in range(number_voc)]
f=open('BOW.txt','w')
cont =''
for i in BoW:
cont += ' '.join(map(str,i)) + '\n'
f.write(cont)
f.close()
f=open('voc.txt','w')
cont = '\n'.join(map(str,voc))
f.write(cont)
f.close()
f=open('invert.txt','w')
cont = '\n'.join(map(str,invert))
f.write(cont)
f.close()
zBoW, zvoc, zinvert = zip(*Vector)
return zBoW, zvoc, zinvert
def load_vector(filenames, captions):
cache_filename = "data_vector.pkl"
cache_path = os.path.join(dir_path, cache_filename)
vectors = cache(cache_path=cache_path,
fn=_load_vector,
filenames= filenames,
captions= captions)
return vectors
def _tf_idf(filenames,captions):
bow, voc, invert = load_vector(filenames, captions)
number_file = len(filenames)
number_voc = len(voc)
tf = np.zeros((number_voc, number_file))
idf = np.zeros(number_voc)
for i in range(number_voc):
idf[i] = round(1+ math.log(number_file/len(invert[i])), 3)
for j in range(number_file):
if bow[i][j] != 0:
tf[i][j] = round(1 + math.log(bow[i][j]), 3)
records = [(np.dot(tf[i],idf[i]), idf[i])
for i in range(len(idf))]
weight, _idf = zip(*records)
return weight, _idf, voc, invert
def load_weight(filenames, captions):
cache_filename = 'weight.pkl'
cache_path = os.path.join(dir_path, cache_filename)
weight = cache(cache_path= cache_path,
fn=_tf_idf,
filenames=filenames,
captions=captions)
return weight