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 	for(int p = 0 ; p < n_eigenface ; p++)
58 	{
59 	   	float min_ = 1000.0;
60 		float max_ = -1000.0;
61 		
62 		for(int i = 0 ; i < n_input ; i++)
63 		{
64 	   		eigenface[i] = pca_machine->eigenvectors[i][p];
65 
66 			if(eigenface[i] < min_) min_ = eigenface[i];
67 			if(eigenface[i] > max_) max_ = eigenface[i];
68 		}
69 		
70 		for(int i = 0 ; i < n_input ; i++)
71 		   	eigenface[i] = (eigenface[i] - min_) / (max_ - min_);
72 
73 		image->copyFrom(width, height, eigenface, "float", 1.0);
74 
75 		char str[256];
76 		sprintf(str, "eigenface%04d.pgm", p);
77 
78 		image->save(str);
79 	}
80 
81 	//
82 	delete image;
83 	delete [] eigenface;
84 	delete pca_machine;
85 	
86 	
87   	return 0;
88 }
89