View Javadoc

1   /**
2    * Copyright (c) 2011, The University of Southampton and the individual contributors.
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without modification,
6    * are permitted provided that the following conditions are met:
7    *
8    *   * 	Redistributions of source code must retain the above copyright notice,
9    * 	this list of conditions and the following disclaimer.
10   *
11   *   *	Redistributions in binary form must reproduce the above copyright notice,
12   * 	this list of conditions and the following disclaimer in the documentation
13   * 	and/or other materials provided with the distribution.
14   *
15   *   *	Neither the name of the University of Southampton nor the names of its
16   * 	contributors may be used to endorse or promote products derived from this
17   * 	software without specific prior written permission.
18   *
19   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
23   * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
26   * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29   */
30  package org.openimaj.demos;
31  
32  import java.io.File;
33  import java.io.IOException;
34  import java.util.ArrayList;
35  import java.util.Collections;
36  import java.util.List;
37  
38  import org.openimaj.feature.local.list.MemoryLocalFeatureList;
39  import org.openimaj.image.feature.dense.gradient.dsift.FloatDSIFTKeypoint;
40  import org.openimaj.io.IOUtils;
41  import org.openimaj.math.matrix.algorithm.pca.ThinSvdPrincipalComponentAnalysis;
42  import org.openimaj.util.array.ArrayUtils;
43  import org.openimaj.util.function.Operation;
44  import org.openimaj.util.parallel.Parallel;
45  
46  import scala.actors.threadpool.Arrays;
47  import Jama.Matrix;
48  
49  public class FVFWDSiftPCAAugment {
50  	static Matrix sample(File dir, int nsamples) throws IOException {
51  		final List<File> files = new ArrayList<File>();
52  
53  		System.out.println("Finding files");
54  		for (final File d : dir.listFiles()) {
55  			if (d.isDirectory()) {
56  				for (final File f : d.listFiles()) {
57  					if (f.getName().endsWith(".bin")) {
58  						files.add(f);
59  					}
60  				}
61  			}
62  		}
63  
64  		System.out.println("Shuffling");
65  		Collections.shuffle(files);
66  
67  		System.out.println("Sampling");
68  		final double[][] data = new double[nsamples][];
69  		final int nPerFile = (int) Math.ceil(nsamples / (double) files.size());
70  		final List<FloatDSIFTKeypoint> samples = new ArrayList<FloatDSIFTKeypoint>();
71  
72  		Parallel.forEach(files, new Operation<File>() {
73  			@Override
74  			public void perform(File f) {
75  				try {
76  					System.out.println(f);
77  
78  					final MemoryLocalFeatureList<FloatDSIFTKeypoint> feats = MemoryLocalFeatureList.read(f,
79  							FloatDSIFTKeypoint.class);
80  
81  					Collections.shuffle(feats);
82  
83  					final MemoryLocalFeatureList<FloatDSIFTKeypoint> s = feats.subList(0, nPerFile);
84  					synchronized (samples) {
85  						samples.addAll(s);
86  					}
87  				} catch (final Exception e) {
88  					e.printStackTrace();
89  				}
90  			}
91  		});
92  
93  		for (int i = 0; i < nsamples; i++) {
94  			data[i] = ArrayUtils.convertToDouble(samples.get(i).descriptor);
95  		}
96  
97  		System.out.println("Done");
98  
99  		return new Matrix(data);
100 	}
101 
102 	@SuppressWarnings("unchecked")
103 	private static void processFiles(final ThinSvdPrincipalComponentAnalysis pca, final File indir, final File outdir)
104 			throws IOException
105 	{
106 		for (final File d : indir.listFiles()) {
107 			if (d.isDirectory()) {
108 
109 				Parallel.forEach(Arrays.asList(d.listFiles()), new Operation<File>() {
110 					@Override
111 					public void perform(File f) {
112 						final Matrix basis = pca.getBasis();
113 						final Matrix tmp = new Matrix(1, 128);
114 						if (f.getName().endsWith(".bin")) {
115 							try {
116 								System.out.println("Processing " + f);
117 
118 								final MemoryLocalFeatureList<FloatDSIFTKeypoint> feats = MemoryLocalFeatureList.read(f,
119 										FloatDSIFTKeypoint.class);
120 
121 								final File outfile = new File(outdir, f.getAbsolutePath().replace(
122 										indir.getAbsolutePath(), ""));
123 								outfile.getParentFile().mkdirs();
124 
125 								for (final FloatDSIFTKeypoint kpt : feats) {
126 									tmp.getArray()[0] = ArrayUtils.convertToDouble(kpt.descriptor);
127 									final double[] proj = tmp.times(basis).getArray()[0];
128 									kpt.descriptor = ArrayUtils.convertToFloat(proj);
129 
130 									kpt.descriptor = Arrays.copyOf(kpt.descriptor, kpt.descriptor.length + 2);
131 									kpt.descriptor[kpt.descriptor.length - 2] = (kpt.x / 125f) - 0.5f;
132 									kpt.descriptor[kpt.descriptor.length - 1] = (kpt.y / 160f) - 0.5f;
133 								}
134 
135 								IOUtils.writeBinary(outfile, feats);
136 								f.delete();
137 							} catch (final Exception e) {
138 
139 							}
140 						}
141 					}
142 				});
143 			}
144 		}
145 	}
146 
147 	/**
148 	 * @param args
149 	 * @throws IOException
150 	 */
151 	public static void main(String[] args) throws IOException {
152 		final File indir = new File("/Volumes/Raid/face_databases/lfw-centre-affine-pdsift/");
153 		final Matrix samples = sample(indir, 100000);
154 
155 		final ThinSvdPrincipalComponentAnalysis pca = new
156 				ThinSvdPrincipalComponentAnalysis(64);
157 		System.out.println("Performing PCA");
158 		pca.learnBasis(samples);
159 		IOUtils.writeToFile(pca, new
160 				File("/Volumes/Raid/face_databases/lfw-centre-affine-pdsift-pca64.bin"));
161 		// final ThinSvdPrincipalComponentAnalysis pca =
162 		// IOUtils.readFromFile(new File(
163 		// "/Volumes/Raid/face_databases/lfw-centre-affine-pdsift-pca64.bin"));
164 
165 		processFiles(pca, indir, new File("/Volumes/Raid/face_databases/lfw-centre-affine-pdsift-pca64" +
166 				"/"));
167 	}
168 }