-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDiscrete_Fourier_Transform.java
269 lines (211 loc) · 8.55 KB
/
Discrete_Fourier_Transform.java
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import java.io.*;
import ij.*;
import ij.io.*;
import ij.ImagePlus;
import ij.process.*;
import ij.gui.*;
import ij.plugin.filter.*;
import java.util.Arrays;
import java.util.Comparator;
public class Discrete_Fourier_Transform implements PlugInFilter
{
ImagePlus reference; // Imagem de referência
int M; // Quantia dos M primeiros coeficientes
int k; // Número de vizinhos mais próximos
int id = 0; // Indice da imagem de referência
String[] imageNames; // Imagens do diretório
boolean showImages; // Exibir ou não as imagens escolhidas
public int setup(String arg, ImagePlus imp)
{
reference = imp;
ImageConverter ic = new ImageConverter(imp);
ic.convertToGray8();
return DOES_ALL;
}
public void run(ImageProcessor img)
{
GenericDialog gd;
SaveDialog sd;
String dir;
String fdist;
ImageAccess[] base;
double choice;
double[][] features;
double[][] distances;
// Interface para definição de parâmetros
gd = new GenericDialog("Transformada discreta de Fourier (DFT)", IJ.getInstance());
gd.addNumericField("Quantia M de fatores a serem registrados: ", 100, 0);
gd.addNumericField("Quantia k de vizinhos a serem buscados: ", 5, 0);
gd.addChoice("Funcao de distancia: ", new String[] { "Manhattan ", "Euclidiana", "Chebyshev"}, "Euclidiana");
gd.addCheckbox("Exibir os K vizinhos escolhidos", false);
gd.showDialog();
if (gd.wasCanceled()) return;
M = (int) gd.getNextNumber();
k = (int) gd.getNextNumber();
fdist = gd.getNextChoice();
showImages = gd.getNextBoolean();
choice = fdist.equals("Manhattan") ? (double) 1 :
fdist.equals("Euclidiana") ? (double) 2 : (double) 0;
// Solicita o diretório das imagens
sd = new SaveDialog("Selecione seu diretorio.", "Selecione seu diretorio.", "");
if (sd.getFileName() == null) return;
dir = sd.getDirectory();
try
{
base = varrerDiretorio(dir); // Retorna as imagens do diretório
features = getFeatures(base); // Retorna os vetores de características
saveThe(features, "features.csv");
distances = distance(features, id, choice); // Calcula as distâncias até a imagem de referência
}
catch(Exception e)
{
IJ.log("\n" + e.getMessage());
return;
}
String originalClass = imageNames[id].replaceAll("[^a-z]","");;
String currentClass = "";
IJ.log("Utilizando a funcao de distancia " + fdist);
IJ.log(">> " + imageNames[(int) distances[0][0]] + " [Imagem de referencia]");
IJ.log("");
int total = new File(dir).list().length;
double acc = 0;
// Mostra as k primeiras imagens
for(int i = 1; i <= k && i < total; i++)
{
double[] image = distances[i];
int imageId = (int) image[0];
double imageDist = image[1];
if(showImages) base[imageId].show("Imagem semelhante nro. " + i);
IJ.log("-> Escolha nro. " + i + " (Distancia = " + String.format("%.3f", imageDist) + "u): " + imageNames[imageId]);
currentClass = imageNames[imageId].replaceAll("[^a-z]","");
if(originalClass.equals(currentClass)) acc += 1. / k;
}
IJ.log("");
IJ.log("Pre amostral = " + String.format("%.3f", acc));
}
public ImageAccess[] varrerDiretorio(String dir) throws Exception
{
ImageAccess[] base;
IJ.log("");
IJ.log("Vasculhando imagens...");
if (!dir.endsWith(File.separator)) dir += File.separator;
imageNames = new File(dir).list(); // lista de arquivos
if (imageNames == null) throw new Exception("Erro: diretorio vazio.");
base = new ImageAccess[imageNames.length];
for (int i = 0; i < imageNames.length; i++) {
File f;
ImagePlus image;
ImageAccess input;
int nx, ny;
IJ.showStatus(i + "/" + imageNames.length + ": " + imageNames[i]); // mostra na interface
IJ.showProgress((double)i / imageNames.length); // barra de progresso
f = new File(dir + imageNames[i]);
if (f.isDirectory()) continue;
image = new Opener().openImage(dir, imageNames[i]); // abre a imagem
if (image == null) continue;
if (image.getTitle().equals(reference.getTitle())) id = i;
input = new ImageAccess(image.getProcessor());
nx = input.getWidth();
ny = input.getHeight();
base[i] = input;
}
IJ.log("");
IJ.showProgress(1.0);
IJ.showStatus("");
return base;
}
public double[][] getFeatures(ImageAccess[] base) throws Exception
{
double[][] features;
IJ.log("");
IJ.log("Aplicando DFT...");
features = new double[base.length][M]; // Guardará os M valores extraídos de N imagens
for (int i = 0; i < base.length; i++) {
ImageAccess img;
img = base[i];
IJ.showStatus(i+"/"+base.length); // mostra na interface
IJ.showProgress((double)i / base.length); // barra de progresso
IJ.log("Analisando imagem " + (i + 1) + "...");
try{ features[i] = DFT.applyDTF(img, M); }
catch(Exception e){ throw e; }
}
IJ.log("");
IJ.showProgress(1.0);
IJ.showStatus("");
return features;
}
public double[][] distance(double[][] features, int id, double c) throws Exception
{
double[][] distances = new double[features.length][2];
double[] referenceFeature = features[id];
double[] normalizedReferenceFeature = normalizeFeatureVector(referenceFeature);
for (int i = 0; i < features.length; i++)
{
double[] normalizedImageFeature = normalizeFeatureVector(features[i]);
try
{
distances[i][0] = i;
distances[i][1] = eDistance(normalizedImageFeature, normalizedReferenceFeature, c);
}
catch(Exception e){ throw e; }
}
Arrays.sort(distances, Comparator.comparingDouble(row -> row[1]));
return distances; // O primeiro item sempre será a própria imagem.
}
private double eDistance(double[] ref, double[] other, double c) throws Exception
{
if(ref.length != other.length) throw new Exception("Erro: Base de dados inconsistente.");
if (c > 0)
{
double sum = 0;
for (int index = 0; index < ref.length; index++)
sum += Math.pow(Math.abs(ref[index] - other[index]), c);
return Math.pow(sum, 1./c);
}
double max = 0;
for (int index = 0; index < ref.length; index++) {
double diff = Math.abs(ref[index] - other[index]);
if(diff > max)
max = diff;
}
return max;
}
private double[] normalizeFeatureVector(double[] featureVector)
{
double[] normalized = new double[featureVector.length];
double N = featureVector.length;
double mean = 0;
double variance = 0;
double stdDev;
for (int i = 0; i < N; i++)
mean += featureVector[i];
mean /= N;
for (int i = 0; i < N; i++)
variance += Math.pow(featureVector[i] - mean, 2);
variance /= (N - 1);
stdDev = Math.sqrt(variance);
for (int i = 0; i < N; i++)
normalized[i] = (featureVector[i] - mean) / stdDev;
return normalized;
}
private void saveThe(double[][] output, String fileName)
{
try (PrintWriter writer = new PrintWriter(new FileWriter(fileName)))
{
for (int j = 0; j < output.length; j++) {
double[] row = output[j];
writer.print(imageNames[j] + ",");
for (int i = 0; i < row.length; i++) {
writer.print(row[i]);
if (i < row.length - 1) writer.print(",");
}
writer.println();
}
writer.close();
}
catch (IOException e)
{
IJ.log("\n" + e.getMessage());
}
}
}