Advertisement
WarPie90

Naïve 2D cross-correlation

Sep 19th, 2015
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.76 KB | None | 0 0
  1. program new;
  2. {$DEFINE E_HIDE_ALL}
  3. {$I SimbaExt_beta/SimbaExt.simba}
  4.  
  5. function MatchTemplate(im,sub:TIntMatrix): TFloatMatrix;
  6. type
  7.   TRGBMatrix = Array of Array of TRGB32;
  8. var
  9.   ImW,ImH,SubW,SubH,area:Int32;
  10.   x,y,xx,yy,iw,ih:Int32;
  11.   cc:Int64;
  12.   pix1,pix2:TRGB32;
  13.   i1,i2:TRGBMatrix;
  14. const
  15.   MAX_SQRGB:Double = (255*255*3.0);
  16. begin
  17.   ImW := Length(Im[0]);
  18.   ImH := Length(Im);
  19.   SubW := Length(Sub[0]);
  20.   SubH := Length(Sub);
  21.  
  22.   SetLength(Result, ImH-SubH, ImW-SubW);
  23.   ih := subh-1;
  24.   iw := subw-1;
  25.   area := subW * subH;
  26.   i1 := TRGBMatrix(im);
  27.   i2 := TRGBMatrix(sub);
  28.  
  29.   for y:=0 to ImH-SubH-1 do
  30.     for x:=0 to ImW-SubW-1 do
  31.     begin
  32.       cc := 0;
  33.       for yy:=0 to ih do
  34.         for xx:=0 to iw do
  35.           Inc(cc, Sqr(i1[y+yy,x+xx].B - i2[yy,xx].B) +
  36.                   Sqr(i1[y+yy,x+xx].G - i2[yy,xx].G) +
  37.                   Sqr(i1[y+yy,x+xx].R - i2[yy,xx].R) );
  38.       Result[y,x] := 1 - (cc / area / MAX_SQRGB); //Result range in 0..1
  39.     end;
  40. end;
  41.  
  42. procedure Debug(Mat:TFloatMatrix);
  43. var
  44.   Debug:TRafBitmap;
  45.   Data:TIntMatrix;
  46.   x,y:Int32;
  47.   H,S,L:Extended;
  48. begin
  49.   Mat := Mat.Normalize(0,100);
  50.   SetLength(Data,Length(Mat), Length(Mat[0]));
  51.   for y:=0 to High(Mat) do
  52.     for x:=0 to High(Mat[0]) do
  53.     begin
  54.       //ColorToHSL(Mat[y,x],H,S,L);
  55.       H := 58;
  56.       S := Mat[y,x];
  57.       L := Mat[y,x];
  58.       Data[y,x] := HSLToColor(H,S,L);
  59.     end;
  60.   Debug.FromMatrix( Data );
  61.   Debug.Debug();
  62.   Debug.Free();
  63. end;
  64.  
  65. var
  66.   BMP,SUB:TRafBitmap;
  67.   Mat:TFloatMatrix;
  68.   m1,m2:TIntMatrix;
  69.   t:Double;
  70. begin
  71.   SUB.Open('rs_cave_sub.png');
  72.   BMP.Open('rs_cave.png');
  73.  
  74.   m1 := BMP.ToMatrix();
  75.   m2 := Sub.ToMatrix();
  76.   t := se.MarkTime();
  77.   mat := MatchTemplate(m1, m2);
  78.   WriteLn(se.MarkTime() - t);
  79.   Debug( mat );
  80. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement