]> Creatis software - clitk.git/blob - vv/vvToolRigidReg.cxx
Add a tolerance when calculate euler angle with rigid transformation
[clitk.git] / vv / vvToolRigidReg.cxx
1 /*=========================================================================
2   Program:   vv                     http://www.creatis.insa-lyon.fr/rio/vv
3
4   Authors belong to:
5   - University of LYON              http://www.universite-lyon.fr/
6   - Léon Bérard cancer center       http://www.centreleonberard.fr
7   - CREATIS CNRS laboratory         http://www.creatis.insa-lyon.fr
8
9   This software is distributed WITHOUT ANY WARRANTY; without even
10   the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11   PURPOSE.  See the copyright notices for more information.
12
13   It is distributed under dual licence
14
15   - BSD        See included LICENSE.txt file
16   - CeCILL-B   http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
17 ===========================================================================**/
18
19 // vv
20 #include "vvToolRigidReg.h"
21 #include "vvSlicer.h"
22 #include <vvBlendImageActor.h>
23
24 // vtk
25 #include <vtkImageData.h>
26 #include <vtkSmartPointer.h>
27 #include <vtkInformation.h>
28 #include <vtkTransform.h>
29 #include <vtkImageActor.h>
30 #include <vtkImageMapper3D.h>
31 #include <vtkOpenGLImageSliceMapper.h>
32
33 // itk
34 #include <itkEuler3DTransform.h>
35
36 // clitk
37 #include "clitkTransformUtilities.h"
38 #include "clitkMatrix.h"
39
40 // qt
41 #include <QMessageBox>
42 #include <QFileDialog>
43 #include <QTextStream>
44
45
46 //------------------------------------------------------------------------------
47 // Create the tool and automagically (I like this word) insert it in
48 // the main window menu.
49 ADD_TOOL(vvToolRigidReg);
50 //------------------------------------------------------------------------------
51
52 //------------------------------------------------------------------------------
53 vvToolRigidReg::vvToolRigidReg(vvMainWindowBase * parent, Qt::WindowFlags f):
54     vvToolWidgetBase(parent, f),
55     vvToolBase<vvToolRigidReg>(parent),
56     Ui::vvToolRigidReg()
57 {
58   // GUI Initialization
59   Ui_vvToolRigidReg::setupUi(mToolWidget);
60   
61   // Set how many inputs are needed for this tool
62   AddInputSelector("Select moving image");
63
64   QFont font = transformationLabel->font();
65   font.setStyleHint(QFont::TypeWriter);
66   transformationLabel->setFont(font);
67
68   mInitialMatrix = vtkSmartPointer<vtkMatrix4x4>::New();
69
70   // Set slider ranges, assume degrees, will not be changed for radians
71   std::vector<QSlider *> transSliders, rotSliders;
72   std::vector<QDoubleSpinBox *> transSBs, rotSBs;
73   GetSlidersAndSpinBoxes(transSliders, rotSliders, transSBs, rotSBs);
74   for(int i=0; i<3; i++) {
75     transSliders[i]->setRange(-2000,2000);
76     rotSliders[i]->setRange(-360,360);
77     transSBs[i]->setRange(-2000,2000);
78     transSBs[i]->setDecimals(3);
79     rotSBs[i]->setRange(-360,360);
80     rotSBs[i]->setDecimals(3);
81   }
82 }
83 //------------------------------------------------------------------------------
84
85 //------------------------------------------------------------------------------
86 vvToolRigidReg::~vvToolRigidReg()
87 {
88 }
89 //------------------------------------------------------------------------------
90
91 //------------------------------------------------------------------------------
92 void vvToolRigidReg::Initialize()
93 {
94   SetToolName("Register");
95   SetToolMenuName("Register manually");
96   SetToolIconFilename(":/common/icons/register.png");
97   SetToolTip("Register manually.");
98   SetToolExperimental(false);
99 }
100 //------------------------------------------------------------------------------
101
102 //------------------------------------------------------------------------------
103 void vvToolRigidReg::InputIsSelected(vvSlicerManager *input)
104 {
105   mInput = input;
106   HideInputSelector();
107   QTabWidget * tab = dynamic_cast<vvMainWindow*>(mMainWindow)->GetTab();
108   move(tab->mapToGlobal(tab->pos()));
109   resize(tab->width(), 0);
110
111   //default image rotation center is the center of the image
112   QString xcord,ycord,zcord;
113   std::vector<double> imageorigin;
114   imageorigin=mInput->GetImage()->GetOrigin();
115   std::vector<int> imageSize = mInput->GetImage()->GetSize();
116   std::vector<double> imageSpacing = mInput->GetImage()->GetSpacing();
117   xcord=xcord.setNum(imageorigin[0]+(imageSize[0]-1)*imageSpacing[0]*0.5, 'g', 3);
118   ycord=ycord.setNum(imageorigin[1]+(imageSize[1]-1)*imageSpacing[1]*0.5, 'g', 3);
119   zcord=zcord.setNum(imageorigin[2]+(imageSize[2]-1)*imageSpacing[2]*0.5, 'g', 3);
120   Xval->setText(xcord);
121   Yval->setText(ycord);
122   Zval->setText(zcord);
123
124   //backup original matrix
125   for(int j=0; j<4; j++)
126     for(int i=0; i<4; i++)
127       // TODO SR and BP: check on the list of transforms and not the first only
128       mInitialMatrix->SetElement(i,j, mCurrentSlicerManager->GetImage()->GetTransform()[0]->GetMatrix()->GetElement(i,j));
129   QString origTransformString(clitk::Get4x4MatrixDoubleAsString(mInitialMatrix).c_str());
130   transformationLabel->setText(origTransformString);
131   SetTransform(mInitialMatrix);
132
133   //connect all sigs to slots
134   connect(resetbutton, SIGNAL(pressed()), this, SLOT(ResetTransform()));
135   connect(loadbutton, SIGNAL(pressed()), this, SLOT(LoadFile()));
136   connect(savebutton, SIGNAL(pressed()), this, SLOT(SaveFile()));
137
138   connect(xtrans_slider, SIGNAL(valueChanged(int)), this, SLOT(SliderChange(int)));
139   connect(ytrans_slider, SIGNAL(valueChanged(int)), this, SLOT(SliderChange(int)));
140   connect(ztrans_slider, SIGNAL(valueChanged(int)), this, SLOT(SliderChange(int)));
141   connect(xrot_slider, SIGNAL(valueChanged(int)), this, SLOT(SliderChange(int)));
142   connect(yrot_slider, SIGNAL(valueChanged(int)), this, SLOT(SliderChange(int)));
143   connect(zrot_slider, SIGNAL(valueChanged(int)), this, SLOT(SliderChange(int)));
144   connect(xtrans_sb, SIGNAL(valueChanged(double)), this, SLOT(SpinBoxChange(double)));
145   connect(ytrans_sb, SIGNAL(valueChanged(double)), this, SLOT(SpinBoxChange(double)));
146   connect(ztrans_sb, SIGNAL(valueChanged(double)), this, SLOT(SpinBoxChange(double)));
147   connect(xrot_sb,   SIGNAL(valueChanged(double)), this, SLOT(SpinBoxChange(double)));
148   connect(yrot_sb,   SIGNAL(valueChanged(double)), this, SLOT(SpinBoxChange(double)));
149   connect(zrot_sb,   SIGNAL(valueChanged(double)), this, SLOT(SpinBoxChange(double)));
150
151   connect(stepTransSpinBox, SIGNAL(valueChanged(double)), this, SLOT(SetTranslationStep(double)));
152   connect(stepRotSpinBox, SIGNAL(valueChanged(double)), this, SLOT(SetRotationStep(double)));
153
154   connect(checkBoxDegrees, SIGNAL(stateChanged(int)), this, SLOT(ToggleSpinBoxAnglesUnit()));
155
156   connect(Xval, SIGNAL(editingFinished()), this, SLOT(ChangeOfRotationCenter()));
157   connect(Yval, SIGNAL(editingFinished()), this, SLOT(ChangeOfRotationCenter()));
158   connect(Zval, SIGNAL(editingFinished()), this, SLOT(ChangeOfRotationCenter()));
159
160   // Init step modifiers
161   stepTransSpinBox->setValue(1.);
162   stepRotSpinBox->setValue(1.);
163 }
164 //------------------------------------------------------------------------------
165
166 //------------------------------------------------------------------------------
167 void vvToolRigidReg::apply()
168 {
169   vvToolWidgetBase::close();
170 }
171 //------------------------------------------------------------------------------
172
173 //------------------------------------------------------------------------------
174 bool vvToolRigidReg::close()
175 {
176   QString warning = "Are you sure you want to reset the original transform?";
177   QMessageBox msgBox(QMessageBox::Warning, tr("Reset transform"),warning, 0, this);
178   msgBox.addButton(tr("Yes"), QMessageBox::AcceptRole);
179   msgBox.addButton(tr("No"), QMessageBox::RejectRole);
180   if (msgBox.exec() == QMessageBox::AcceptRole) {
181     SetTransform(mInitialMatrix);
182     return vvToolWidgetBase::close();
183   }
184   return false;
185 }
186 //------------------------------------------------------------------------------
187
188 //------------------------------------------------------------------------------
189 void vvToolRigidReg::reject()
190 {
191   return vvToolWidgetBase::reject();
192 }
193 //------------------------------------------------------------------------------
194
195 //------------------------------------------------------------------------------
196 void vvToolRigidReg::SetTranslationStep(double v)
197 {
198   xtrans_sb->setSingleStep(v);
199   ytrans_sb->setSingleStep(v);
200   ztrans_sb->setSingleStep(v);
201 }
202 //------------------------------------------------------------------------------
203
204 //------------------------------------------------------------------------------
205 void vvToolRigidReg::SetRotationStep(double v)
206 {
207   xrot_sb->setSingleStep(v);
208   yrot_sb->setSingleStep(v);
209   zrot_sb->setSingleStep(v);
210 }
211 //------------------------------------------------------------------------------
212
213 //------------------------------------------------------------------------------
214 void vvToolRigidReg::SliderChange(int newVal)
215 {
216   std::vector<QSlider *> transSliders, rotSliders;
217   std::vector<QDoubleSpinBox *> transSBs, rotSBs;
218   GetSlidersAndSpinBoxes(transSliders, rotSliders, transSBs, rotSBs);
219   for(int i=0; i<3; i++) {
220     if(transSliders[i] == QObject::sender()) {
221       transSBs[i]->setValue(newVal);
222     }
223     if(rotSliders[i] == QObject::sender()) {
224       double rad = (checkBoxDegrees->checkState()==Qt::Unchecked)?itk::Math::pi/180.:1.;
225       rotSBs[i]->setValue(newVal*rad);
226     }
227   }
228 }
229 //------------------------------------------------------------------------------
230
231 //------------------------------------------------------------------------------
232 void vvToolRigidReg::SpinBoxChange(double newVal)
233 {
234   std::vector<QSlider *> transSliders, rotSliders;
235   std::vector<QDoubleSpinBox *> transSBs, rotSBs;
236   GetSlidersAndSpinBoxes(transSliders, rotSliders, transSBs, rotSBs);
237   for(int i=0; i<3; i++) {
238     if(transSBs[i] == QObject::sender()) {
239       transSliders[i]->blockSignals(true);
240       transSliders[i]->setValue(itk::Math::Round<double,double>(newVal));
241       transSliders[i]->blockSignals(false);
242     }
243     if(rotSBs[i] == QObject::sender()) {
244       double rad = (checkBoxDegrees->checkState()==Qt::Unchecked)?180./itk::Math::pi:1.;
245       rotSliders[i]->blockSignals(true);
246       rotSliders[i]->setValue(itk::Math::Round<double,double>(newVal*rad));
247       rotSliders[i]->blockSignals(false);
248     }
249   }
250
251   // Compute transform and set
252   // TODO SR and BP: check on the list of transforms and not the first only
253   vtkSmartPointer<vtkTransform> transform_final=mInput->GetImage()->GetTransform()[0];
254   transform_final->Identity();
255   transform_final->PostMultiply();
256
257   // Rotations
258   double x=0, y=0 ,z=0;
259   x= Xval->text().toDouble();
260   y= Yval->text().toDouble();
261   z= Zval->text().toDouble();
262   double rad = (checkBoxDegrees->checkState()==Qt::Unchecked)?180./itk::Math::pi:1.;
263   transform_final->Translate(-x,-y,-z);
264   transform_final->RotateY(yrot_sb->value()*rad);
265   transform_final->RotateX(xrot_sb->value()*rad);
266   transform_final->RotateZ(zrot_sb->value()*rad);
267   transform_final->Translate(x,y,z);
268
269   // Translation
270   transform_final->Translate(xtrans_sb->value(),
271                              ytrans_sb->value(),
272                              ztrans_sb->value());
273   transform_final->Update();
274   SetTransform(transform_final->GetMatrix());
275 }
276 //------------------------------------------------------------------------------
277
278 //------------------------------------------------------------------------------
279 void vvToolRigidReg::ToggleSpinBoxAnglesUnit()
280 {
281   double rad = (checkBoxDegrees->checkState()==Qt::Unchecked)?itk::Math::pi/180.:180./itk::Math::pi;
282   std::vector<QSlider *> transSliders, rotSliders;
283   std::vector<QDoubleSpinBox *> transSBs, rotSBs;
284   GetSlidersAndSpinBoxes(transSliders, rotSliders, transSBs, rotSBs);
285   for(int i=0; i<3; i++) {
286     rotSBs[i]->blockSignals(true);
287     rotSBs[i]->setValue(rotSBs[i]->value()*rad);
288     rotSBs[i]->blockSignals(false);
289   }
290 }
291 //------------------------------------------------------------------------------
292
293 //------------------------------------------------------------------------------
294 void vvToolRigidReg::SaveFile()
295 {
296   //Write the Transformation Matrix
297   std::string absPath = mCurrentSlicerManager->GetFileName();
298   absPath = itksys::SystemTools::GetFilenameWithoutExtension(absPath) + std::string(".mat");
299   QString filename = QFileDialog::getSaveFileName(this, tr("Save Transformation Matrix File"),
300                                             absPath.c_str(),
301                                             tr("Text (*.mat *.txt *.doc *.rtf)"));
302
303   QFile file(filename);
304   if (file.open(QFile::WriteOnly | QFile::Truncate)) {
305     // TODO SR and BP: check on the list of transforms and not the first only
306     vtkMatrix4x4* matrix = mCurrentSlicerManager->GetImage()->GetTransform()[0]->GetMatrix();
307     QString matrixStr = clitk::Get4x4MatrixDoubleAsString(matrix,16).c_str();
308     QTextStream out(&file);
309     out << matrixStr;
310   }
311   else
312   {
313     QMessageBox::information(this,"Error","Unable to open file for writing");
314   }
315 }
316 //------------------------------------------------------------------------------
317
318 //------------------------------------------------------------------------------
319 void vvToolRigidReg::LoadFile()
320 {
321   //Open File to read the transformation parameters
322   QString file = QFileDialog::getOpenFileName(
323                    this,
324                    "Choose the filename for the transformation matrix",
325                    vtksys::SystemTools::GetFilenamePath(mCurrentSlicerManager->GetFileName()).c_str(),
326                    "Text (*.mat *.txt *.rtf *.doc)");
327    if (file.isEmpty())
328      return;
329
330
331   itk::Matrix<double, 4, 4> itkMat = clitk::ReadMatrix3D(file.toStdString());
332   vtkSmartPointer<vtkMatrix4x4> matrix = vtkSmartPointer<vtkMatrix4x4>::New();
333   matrix->Identity();
334   for(int j=0; j<4; j++)
335     for(int i=0; i<4; i++)
336       matrix->SetElement(j,i,itkMat[j][i]);
337   SetTransform(matrix);
338 }
339 //------------------------------------------------------------------------------
340   
341 //------------------------------------------------------------------------------
342 void vvToolRigidReg::ChangeOfRotationCenter()
343 {
344   // TODO SR and BP: check on the list of transforms and not the first only
345   SetTransform(mCurrentSlicerManager->GetImage()->GetTransform()[0]->GetMatrix());
346 }
347 //------------------------------------------------------------------------------
348
349 //------------------------------------------------------------------------------
350 void vvToolRigidReg::ResetTransform()
351 {
352   SetTransform(mInitialMatrix);
353 }
354 //------------------------------------------------------------------------------
355
356 //------------------------------------------------------------------------------
357 void vvToolRigidReg::SetTransform(vtkMatrix4x4 *matrix)
358 {
359   vtkSmartPointer<vtkTransform> transform=vtkSmartPointer<vtkTransform>::New();
360   // TODO SR and BP: check on the list of transforms and not the first only
361   mCurrentSlicerManager->GetImage()->GetTransform()[0]->SetMatrix(matrix);
362   transform->Update();
363   Render();
364   dynamic_cast<vvMainWindow*>(mMainWindow)->ImageInfoChanged();
365
366   // Compute parameters from transfer using itk Euler transform
367   itk::Euler3DTransform<double>::CenterType center;
368   center[0] = Xval->text().toDouble();
369   center[1] = Yval->text().toDouble();
370   center[2] = Zval->text().toDouble();
371   itk::Euler3DTransform<double>::MatrixType rotMat;
372   itk::Euler3DTransform<double>::OutputVectorType transVec;
373   for(int i=0; i<3; i++) {
374     transVec[i] = matrix->GetElement(i,3);
375     for(int j=0; j<3; j++)
376       rotMat[i][j] = matrix->GetElement(i,j);
377   }
378   itk::Euler3DTransform<double>::Pointer euler;
379   euler = itk::Euler3DTransform<double>::New();
380   euler->SetCenter(center);
381   try {
382     euler->SetMatrix(rotMat,0.00001);
383   } catch (itk::ExceptionObject) {
384     QString warning = "The matrice is a non-orthogonal rotation matrix.\nThe manual registration doesn't work.";
385     QMessageBox msgBox(QMessageBox::Warning, tr("Reset transform"),warning, 0, this);
386     msgBox.addButton(tr("OK"), QMessageBox::AcceptRole);
387     if (msgBox.exec() == QMessageBox::AcceptRole) {
388         //SetTransform(mInitialMatrix);
389         vvToolWidgetBase::close();
390     }
391   }
392   euler->SetOffset(transVec);
393
394   // Modify GUI according to the new parameters
395   std::vector<QSlider *> transSliders, rotSliders;
396   std::vector<QDoubleSpinBox *> transSBs, rotSBs;
397   GetSlidersAndSpinBoxes(transSliders, rotSliders, transSBs, rotSBs);
398   for(int i=0; i<3; i++) {
399     // Translations
400     transSBs[i]->blockSignals(true);
401     transSBs[i]->setValue( euler->GetParameters()[i+3] );
402     transSBs[i]->blockSignals(false);
403     transSliders[i]->blockSignals(true);
404     transSliders[i]->setValue( itk::Math::Round<double,double>(euler->GetParameters()[i+3]) );
405     transSliders[i]->blockSignals(false);
406
407     // Rotations
408     double rad = (checkBoxDegrees->checkState()==Qt::Checked)?180./itk::Math::pi:1.;
409     double angleDiff = euler->GetParameters()[i]-rotSBs[i]->value()/rad+2*itk::Math::pi;
410     angleDiff = angleDiff - 2*itk::Math::pi*itk::Math::Round<double,double>(angleDiff/(2*itk::Math::pi));
411     if(abs(angleDiff)>1.e-4) {
412       rotSBs[i]->blockSignals(true);
413       rotSBs[i]->setValue( euler->GetParameters()[i]*rad );
414       rotSBs[i]->blockSignals(false);
415     }
416     int iAngle = itk::Math::Round<int,double>(euler->GetParameters()[i]*180./itk::Math::pi);
417     if((iAngle-rotSliders[i]->value()+360)%360!=0) {
418       rotSliders[i]->blockSignals(true);
419       rotSliders[i]->setValue(iAngle);
420       rotSliders[i]->blockSignals(false);
421     }
422   }
423 }
424 //------------------------------------------------------------------------------
425
426 //------------------------------------------------------------------------------
427 // Just an helper function to shorten the code with loops on sliders and spinboxes
428 void vvToolRigidReg::GetSlidersAndSpinBoxes(std::vector<QSlider *>&transSliders, std::vector<QSlider *>&rotSliders,
429                                             std::vector<QDoubleSpinBox *>&transSBs, std::vector<QDoubleSpinBox *>&rotSBs)
430 {
431   transSliders.push_back(xtrans_slider);
432   transSliders.push_back(ytrans_slider);
433   transSliders.push_back(ztrans_slider);
434
435   rotSliders.push_back(xrot_slider);
436   rotSliders.push_back(yrot_slider);
437   rotSliders.push_back(zrot_slider);
438
439   transSBs.push_back(xtrans_sb);
440   transSBs.push_back(ytrans_sb);
441   transSBs.push_back(ztrans_sb);
442
443   rotSBs.push_back(xrot_sb);
444   rotSBs.push_back(yrot_sb);
445   rotSBs.push_back(zrot_sb);
446 }
447 //------------------------------------------------------------------------------
448
449 //------------------------------------------------------------------------------
450 void vvToolRigidReg::ExtentMax(const double pointExtent[8][4], double maxExtent[2][3])
451 {
452     double max, min;
453     for (int i=0; i<3; ++i) {
454         max = pointExtent[0][i];
455         min = pointExtent[0][i];
456         for (int j=1; j<8; ++j) {
457             if (pointExtent[j][i] > max) {
458                 max = pointExtent[j][i];
459             }
460             if (pointExtent[j][i] < min) {
461                 min = pointExtent[j][i];
462             }
463         }
464         maxExtent[0][i] = min;
465         maxExtent[1][i] = max;
466     }
467 }
468 //------------------------------------------------------------------------------
469
470 //------------------------------------------------------------------------------
471 void vvToolRigidReg::Render()
472 {
473 for (int i=0; i<mCurrentSlicerManager->GetNumberOfSlicers(); i++) {
474     mCurrentSlicerManager->GetSlicer(i)->ForceUpdateDisplayExtent();
475     mCurrentSlicerManager->GetSlicer(i)->Render();
476 }
477 }
478 //------------------------------------------------------------------------------
479