Basic Image AlgorithmS Library  2.8.0
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
ExampleAlignment.cpp
1 /*
2 This file is part of the BIAS library (Basic ImageAlgorithmS).
3 
4 Copyright (C) 2003-2009 (see file CONTACT for details)
5  Multimediale Systeme der Informationsverarbeitung
6  Institut fuer Informatik
7  Christian-Albrechts-Universitaet Kiel
8 
9 
10 BIAS is free software; you can redistribute it and/or modify
11 it under the terms of the GNU Lesser General Public License as published by
12 the Free Software Foundation; either version 2.1 of the License, or
13 (at your option) any later version.
14 
15 BIAS is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU Lesser General Public License for more details.
19 
20 You should have received a copy of the GNU Lesser General Public License
21 along with BIAS; if not, write to the Free Software
22 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 */
24 
25 /**
26  @example ExampleAlignment.cpp
27  @relates ImageAlignment, TextureTransformHomography,TextureTransformAffine
28  @brief Alignment example
29  @ingroup g_examples
30  @author woelk
31 */
32 
33 #include <Base/Image/Image.hh>
34 #include <Base/ImageUtils/ImageDraw.hh>
35 #include <Base/Image/ImageIO.hh>
36 #include <Base/Image/ImageConvert.hh>
37 #include <Base/Geometry/HomgPoint2D.hh>
38 #include <Base/Debug/TimeMeasure.hh>
39 #include <Image/TextureTransformHomography.hh>
40 #include <Image/TextureTransformSimilar.hh>
41 #include <Image/TextureTransformAffine.hh>
42 #include <Image/TextureTransformDisplacement.hh>
43 #include <Image/TextureTransformDisparity.hh>
44 #include <Base/Math/Random.hh>
45 
46 #include <Matcher2D/ImageAlignment.hh>
47 #include <Image/TextureMapping.hh>
48 #include <iostream>
49 #include <iomanip>
50 
51 using namespace BIAS;
52 using namespace std;
53 
54 // loads an image and converts to single channel float image
55 int LoadImage(const string& name, Image<float>& im)
56 {
57  ImageBase baseim;
58 
59  // load image
60  if (ImageIO::Load(name, baseim)!=0){
61  BIASERR("error loading image "<<name);
62  return -1;
63  }
64  // convert to float
65  if (ImageConvert::ConvertST(baseim, im, ImageBase::ST_float)!=0){
66  BIASERR("error converting image "<<name);
67  return -2;
68  }
69  // convert to grey if necessary
70  if (im.GetChannelCount()!=1){
71  if (ImageConvert::ToGrey(im, im)!=0){
72  BIASERR("error converting image to grey "<<name);
73  return -3;
74  }
75  }
76  im.SetMetaData(*baseim.GetMetaData());
77 
78  return 0;
79 }
80 
81 
82 // the main function
83 int main(int argc, char*argv[])
84 {
85  // read parameter from command line
86  if (argc<2) {
87  cerr << argv[0] << " <image> "<< endl;
88  return -1;
89  }
90  // load first image
91  Image<float> im[2];
92  if (LoadImage(argv[1], im[0]) != 0) {
93  BIASERR("error loading image " << argv[1]);
94  return -1;
95  }
96  // if (LoadImage(argv[2], im[1]) != 0) {
97  // BIASERR("error loading image " << argv[2]);
98  // return -1;
99  // }
100 
101  im[1] = im[0];
102  //Gauss<float, float> smoother;
103  //smoother.SetSigma(2.0);
104  //smoother.Filter(im[1], im[0]);
105  im[1].SetZero();
106 
107  // get the point to track
108  HomgPoint2D p[2];
109  p[0][2] = p[1][2] = 1.0;
110  p[0][0] = im[0].GetWidth()/2.0;
111  p[0][1] = im[0].GetHeight()/2.0;
112 
113  LocalAffineFrame LAF;
114  Vector2<double> thepoint(p[0][0],p[0][1] );
115  LAF.SetT(thepoint);
116  LAF.SetA(Matrix<double>(2,2,MatrixIdentity)*(im[0].GetWidth()/16.0));
117 
118  Random R;
119  Vector<double> par, origpar;
120  Matrix<double> cov;
121  TextureTransform *TT = NULL;
122  int mode = 3;
123  switch (mode) {
124  case 4:TT = new TextureTransformHomography;
125  cout<<"Testing HOMOGRAPHY"<<endl;
126  par.newsize(6); par[0] = 0.1; par[1] = 0.1; par[2] = 0.1; par[3] = 0.1;
127  par[4] = 1; par[5] = -1; par[6] = 0.01; par[7] = -0.01;
128  break;
129  case 3:TT = new TextureTransformAffine;
130  cout<<"Testing AFFINITY"<<endl;
131  par.newsize(6); par[0] = 0.2; par[1] = -0.1; par[2] = -0.2; par[3] = 0.3;
132  par[4] = 1; par[5] = -1;
133  par[0] = cos(0.4)-1.0; par[1] = sin(0.4); par[2] = -sin(0.4); par[3] = cos(0.4)-1.0;
134  par[4] = -2; par[5] = 2;
135  break;
136  case 2:TT = new TextureTransformSimilar;
137  cout<<"Testing SIMILARITY"<<endl;
138  par.newsize(4); par[0] = -0.3; par[1] = 0.3; par[2] = 1; par[3] = -1; break;
139  case 1:TT = new TextureTransformDisplacement;
140  cout<<"Testing DISPLACEMENT"<<endl;
141  par.newsize(2); par[0] = -1; par[1] = 1; break;
142  default:TT = new TextureTransformDisparity;
143  cout<<"Testing DISPARITY"<<endl;
144  par.newsize(1); par[0]= 1; break;
145  }
146  cov.newsize(par.Size(), par.Size());
147  cov.SetIdentity();
148 
149  cout<<"using parameters "<<par<<endl;
150  origpar = par;
151  TT->SetParameters(par);
152  TextureTransformSimilar* pTTS = dynamic_cast<TextureTransformSimilar*>(TT);
153  if (pTTS!=NULL) {
154  Vector2<double> thepoint2(thepoint);
155  //thepoint2[1] = 0;thepoint2[0] = 0;
156  cout<<"setting origin !"<<thepoint2<<endl;
157  pTTS->SetOrigin(thepoint2);
158  }
159  TextureTransformAffine* pTTA = dynamic_cast<TextureTransformAffine*>(TT);
160  if (pTTA!=NULL) {
161  Vector2<double> thepoint2(thepoint);
162  //thepoint2[1] = 0;thepoint2[0] = 0;
163  cout<<"setting origin !"<<thepoint2<<endl;
164  pTTA->SetOrigin(thepoint2);
165  }
166 
167  ImageAlignment IA;
168  IA.SetTextureTransform(*TT);
169  IA.AddDebugLevel(D_IMAGEALIGNMENT_PROGRESS);
170  //IA.AddDebugLevel(D_IMAGEALIGNMENT_PARAMETER);
171  //IA.AddDebugLevel(D_IMAGEALIGNMENT_PERPIXEL);
172  IA.AddDebugLevel(D_IMAGEALIGNMENT_IMAGES);
173 
174  IA.SetMaxIterations(50);
175  IA.SetUpdateThreshold(0.01);
176 
177 
178  // map with random parameters
180 
181  Vector<double> invParams = TT->GetInverseParameters();
182  TT->SetParameters(invParams);
183 
184  im[1] = im[0];
185  im[0].SetZero();
186  TM.SetTextureTransform(*TT);
187  TM.Map(im[1], im[0], MapBilinear);
188 
189  // change brightness of image 2
190  bool brightnesschange = true;
191  if (false) {//(brightnesschange) {
192  float *pData = im[1].GetImageData();
193  const float *pDataEnd = im[1].GetImageData()+im[1].GetPixelCount();
194  do {
195  *pData = 0.9f * *pData + 20.0f;
196  } while (pData++ < pDataEnd);
197  }
198  IA.SetAffineBrightnessInvariance(brightnesschange);
199  IA.SetDampening(1.0);
200  // some noise on image 2
201  double pixelnoise = 0.0;
202  if (pixelnoise>0.0) {
203  float *pData = im[1].GetImageData();
204  const float *pDataEnd = im[1].GetImageData()+im[1].GetPixelCount();
205  do {
206  *pData = R.GetNormalDistributed(*pData, pixelnoise);
207  } while (pData++ < pDataEnd);
208  }
209  //ImageIO::Save("im0.mip", im[0]);
210  //ImageIO::Save("im1.mip", im[1]);
211  ImageIO::Save("im0.mip", im[0]);
212  ImageIO::Save("im1.mip", im[1]);
213 
214  // some noise on parameters to start estimate
215  cov.SetIdentity();
216  cov *= 1e-10;
217  double parameternoise = 0.2;
218  if (parameternoise>0.0) {
219  for (int i=par.Size()-1; i>=0; i--) {
220  par[i] *= R.GetUniformDistributed(1.0-parameternoise, 1.0+parameternoise);
221  cov[i][i] = par[i]*par[i]*parameternoise*parameternoise + 1e-10;
222  }
223  }
224 
225  // prepare alignment
226  PyramidImage<float> i1,i2;
227  i1.Init(im[0], 4);
228  i2.Init(im[1], 4);
229 
230  cout<<"Setting alignment pixels"<<endl<<flush;
232  cout<<"Aligning ..."<<endl<<flush;
233 
234  Vector<double> startpar = par;
235  // align images
236  //int result = IA.Align(i1, i2, par, cov, -1);
237  int result = //IA.AutoAlign(i1, i2, par, cov);
238  IA.StrictPyramidAlign(i1, i2, par, cov);
239 
240  // show results
241  double scale=0, offset=0;
242  IA.GetLastBrightnessChange(scale, offset);
243  cout << "result: " << result << ", "
244  << p[0] << " -> " << par << ", "<<endl;
245  cout<<"original parameters were "<<origpar<<endl;
246  cout<<"optimization started at "<<startpar<<endl;
247  cout<<"Brightness change is "<<std::setprecision(3)<<scale<<" "<<offset<<endl;
248  return 0;
249 }
250 
analytic properties of affine image warp
virtual Vector< double > GetInverseParameters() const
returns parameter vector which undoes the current warp
analytic properties of homography transformation of an image
class HomgPoint2D describes a point with 2 degrees of freedom in projective coordinates.
Definition: HomgPoint2D.hh:67
void AddDebugLevel(const long int lv)
Definition: Debug.hh:355
void SetOrigin(const Vector2< double > &origin)
origin relative to which rotation and scale is performed
analytic properties of x-displacement
void GetLastBrightnessChange(double &scale, double &shift)
return relative affine transform between i1 and i2 if AffineBrightnessInvariance was active ...
void SetAffineBrightnessInvariance(bool bi)
enable brightness variance and offset invariant computation
affine transformation of 2D image plane which relates image coordinate system and local affine featur...
int StrictPyramidAlign(const PyramidImage< float > &I1, const PyramidImage< float > &I2, Vector< double > &params, Matrix< double > &Cov)
aligns image1 with image2 with respect to parameters params, traditional pyramid based alignment is u...
analytic properties of 2D image displacement
Matrix< T > & newsize(Subscript M, Subscript N)
Definition: cmat.h:269
MetaData * GetMetaData()
Definition: ImageBase.hh:456
float image storage type
Definition: ImageBase.hh:118
class for representing parameterized image warps, such as homography, displacement, ...
unsigned int Size() const
length of the vector
Definition: Vector.hh:143
double GetUniformDistributed(const double min, const double max)
on succesive calls return uniform distributed random variable between min and max ...
Definition: Random.hh:84
void SetA(const BIAS::Matrix2x2< double > &A, const BIAS::Matrix< double > &cov=BIAS::Matrix< double >(4, 4, BIAS::MatrixZero))
return affine matrix
unsigned int GetWidth() const
Definition: ImageBase.hh:312
void SetAlignmentPixelsRectangular(const LocalAffineFrame &LAF, int numberOfPixels=-1)
choose any rectangular tracking region and resolution
Vector< T > & newsize(Subscript N)
Definition: vec.h:220
void SetUpdateThreshold(const double maxerr)
if a step smaller (norm L2) than this is taken, convergence is declared and the system finishes ...
static int ConvertST(const BIAS::ImageBase &source, BIAS::ImageBase &dest, ImageBase::EStorageType targetST)
Function to convert the storage type of images e.g.
unsigned int GetChannelCount() const
returns the number of Color channels, e.g.
Definition: ImageBase.hh:382
void SetT(const BIAS::Vector2< double > &T, const BIAS::Matrix< double > &cov=BIAS::Matrix< double >(2, 2, BIAS::MatrixZero))
return offset
void Init(const Image< StorageType > &image, const unsigned py_size=0)
copy image into level 0 and create other levels according to parameters set so far (pyramidsize...
unsigned int GetHeight() const
Definition: ImageBase.hh:319
int Map(const Image< InputStorageType > &src, Image< OutputStorageType > &sink, InterpolationMethod=MapTrilinear, bool newSink=false, double SuperSampling=1.0)
backward mapping with various interpolations
Inverse Compositional Image Alignment (&quot;Registration&quot;)
void SetTextureTransform(const TextureTransform &T)
create clone of your texture tranform and set for mapping
static int Save(const std::string &filename, const ImageBase &img, const enum TFileFormat FileFormat=FF_auto, const bool sync=BIAS_DEFAULT_SYNC, const int c_jpeg_quality=BIAS_DEFAULT_IMAGE_QUALITY, const bool forceNewID=BIAS_DEFAULT_FORCENEWID, const bool &writeMetaData=true)
Export image as file using extrnal libs.
Definition: ImageIO.cpp:725
void SetIdentity()
Converts matrix to identity matrix.
Definition: Matrix.cpp:383
const StorageType * GetImageData() const
overloaded GetImageData() from ImageBase
Definition: Image.hh:137
static int Load(const std::string &FileName, ImageBase &img)
first tries a call to Read MIP image and if that fails, tries to Import Image with all other availabl...
Definition: ImageIO.cpp:141
virtual void SetParameters(const Vector< double > &p)=0
override the current state with the new parameters, the meaning of the parameters is defined in the d...
void SetOrigin(const Vector2< double > &origin)
origin relative to which rotation and scale is performed
void SetTextureTransform(const TextureTransform &T)
pass object type which holds texture transform
double GetNormalDistributed(const double mean, const double sigma)
on succesive calls return normal distributed random variable with mean and standard deviation sigma ...
Definition: Random.hh:71
void SetDampening(const double &dampening)
adds a dampening d to hessian&#39;s diag
void SetMetaData(const MetaData &m)
Definition: ImageBase.hh:470
unsigned long int GetPixelCount() const
returns number of pixels in image
Definition: ImageBase.hh:422
This is the base class for images in BIAS.
Definition: ImageBase.hh:102
Maps source pixel to sink pixel given any TextureTransform.
class for producing random numbers from different distributions
Definition: Random.hh:51
void SetZero()
zeroes the image
Definition: ImageBase.hh:83
void SetMaxIterations(const int maxiter)
number of iterations, before the system stops unsuccessfully
static int ToGrey(const ImageBase &source, ImageBase &dest)
wrapper for the templated function ToGrey