pca2pgm.cc

 1 const char *help = "\
 2 progname: pca2pgm.cc\n\
 3 code2html: This program reads a PCA model and saves eigenfaces.\n\
 4 version: Torch3 vision2.0, 2003-2005\n\
 5 (c) Sebastien Marcel (marcel@idiap.ch)\n";
 6 
 7 #include "PCAMachine.h"
 8 #include "ImageGray.h"
 9 #include "CmdLine.h"
10 
11 using namespace Torch;
12 
13 int main(int argc, char *argv[])
14 {
15 	char *model_filename;
16 	int width, height;
17 	int n_eigenface;
18 	real variance;
19 	bool verbose;
20 	int verbose_level;
21 	CmdLine cmd;
22 	cmd.setBOption("write log", false);
23 	
24 	cmd.info(help);
25 	cmd.addText("\nArguments:");
26 	cmd.addSCmdArg("model filename", &model_filename, "PCA model filename");
27 	cmd.addICmdArg("width", &width, "width");
28 	cmd.addICmdArg("height", &height, "height");
29 	cmd.addText("\nOptions:");
30 	cmd.addICmdOption("-eigenface", &n_eigenface, 2, "number of eigenface");
31 	cmd.addRCmdOption("-variance", &variance, 0.95, "variance");
32 	cmd.addBCmdOption("-verbose", &verbose, false, "verbose");
33 	cmd.addICmdOption("-verbose_level", &verbose_level, 0, "verbose level");
34 	cmd.read(argc, argv);
35 
36 	int n_input = width * height;
37 
38 	//
39 	PCAMachine *pca_machine = NULL;
40 	pca_machine = new PCAMachine(n_input);
41 
42 	//
43 
44 	print("Loading PCA model: %s ...\n", model_filename);
45 
46    	pca_machine->load(model_filename, NULL);
47 	   
48 	//
49 	pca_machine->setIOption("verbose_level", verbose_level);
50 	pca_machine->setROption("variance", variance);
51 	pca_machine->init();
52 
53 	float *eigenface = new float [n_input];
54 
55 	ImageGray *image = new ImageGray(width, height);
56 	
57 	image->copyFrom(width, height, pca_machine->Xm, "float", 1.0);
58 	image->save("mean.pgm");
59 
60 	for(int p = 0 ; p < n_eigenface ; p++)
61 	{
62 	   	float min_ = 1000.0;
63 		float max_ = -1000.0;
64 		
65 		for(int i = 0 ; i < n_input ; i++)
66 		{
67 	   		eigenface[i] = pca_machine->eigenvectors[i][p];
68 
69 			if(eigenface[i] < min_) min_ = eigenface[i];
70 			if(eigenface[i] > max_) max_ = eigenface[i];
71 		}
72 		
73 		for(int i = 0 ; i < n_input ; i++)
74 		   	eigenface[i] = (eigenface[i] - min_) / (max_ - min_);
75 
76 		image->copyFrom(width, height, eigenface, "float", 1.0);
77 
78 		char str[256];
79 		sprintf(str, "eigenface%04d.pgm", p);
80 
81 		image->save(str);
82 	}
83 
84 	//
85 	delete image;
86 	delete [] eigenface;
87 	delete pca_machine;
88 	
89 	
90   	return 0;
91 }
92