Mathematicaで固有顔

[R][画像処理]Rで固有顔?
[R][画像処理]Rで固有顔&近似画像

今回は先生から頂いた手描きっぽい顔画像200枚程度を用いて固有顔を求めます。

画像のサイズはあらかじめ32x32までダウンスケールされてるんだよ。

256×256でやってみました。
画像は用意されている202枚。あらかじめファイルの名前はimage001〜image256.bmpにしておきます。(これはIrfanViewでやりました)

(* 画像枚数 *)
num = 202;

(* 画像サイズ(正方) *)
size = 256;

(* データの読み込み *)
data =
  Table[
   Which[
    i < 10,
    mypath = 
     "mathematica/class/Faces/repng256/image00" <> ToString[i] <> 
      ".bmp",
    i < 100,
    mypath = 
     "mathematica/class/Faces/repng256/image0" <> ToString[i] <> 
      ".bmp",
    i < 1000,
    mypath = 
     "mathematica/class/Faces/repng256/image" <> ToString[i] <> ".bmp"
    ];
   Import[mypath, "GrayLevels"]
   , {i, 1, num}];


data2 = Map[Flatten[#] &, data];
(* 平均顔の作成 *)
ave = Mean[data2];

(* 各画像の平均からの差分を計算 *)
data3 = Map[# - ave &, data2];

(* データ量が大きいので、data,data2を解放 *)
Clear[data, data2];

(* SVD(特異値分解)で固有値・固有ベクトルを計算する *)
A = SingularValueDecomposition[data3, 202];

(* 固有ベクトルを取り出し、変数eigenfacesに入れる *)
eigenfaces = Transpose[A[[3]]];


(* 固有顔をずらっと表示 *)
Grid[
 Partition[
  Flatten[
   {Table[
     Image[  Partition[ Rescale[eigenfaces[[i]]], size] , 
      ImageSize -> Tiny ]
     , {i, 1, 202}],
    {{}, {}, {}, {}, {}, {}}}, 1]
  , 8]
 ]



mypath = "mathematica/class/Faces/repng256/(近似したい画像名).bmp";
input1 = Import[mypath, "GrayLevels"];

(* 重みの計算 *)
weight = Table[Flatten[input2].eigenfaces[[i]], {i, 1, 202}];



(* aprxImage の初期値として平均顔を入力する *)
aveImage = Partition[ave, size];
aprxImage = aveImage;


(* 1202次近似を計算する *)
A = Table[
   aprxImage += Partition[weight[[i]]  eigenfaces[[i]], size];
   Image[Rescale[aprxImage], ImageSize -> Tiny]
   , {i, 1, 202}];

(* 近似された画像を表示 *)
Grid[
 Partition[
  Flatten[
   {Image[Rescale[input1], ImageSize -> Tiny],
    Image[Rescale[aveImage], ImageSize -> Tiny],
    Table[A[[i]], {i, 1, 100, 1}],
    {{}, {}, {}, {}, {}, {}, {}}}
   , 1]
  , 8]
 ]

それにしても、mathematicaはてなシンタックス・ハイライトに対応してないので見づらくてしょうがないです。