1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkMNITransformWriter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*=========================================================================
Copyright (c) 2006 Atamai, Inc.
Use, modification and redistribution of the software, in source or
binary forms, are permitted provided that the following terms and
conditions are met:
1) Redistribution of the source code, in verbatim or modified
form, must retain the above copyright notice, this license,
the following disclaimer, and any notices that refer to this
license and/or the following disclaimer.
2) Redistribution in binary form must include the above copyright
notice, a copy of this license and the following disclaimer
in the documentation or with other materials provided with the
distribution.
3) Modified copies of the source code must be clearly marked as such,
and must not be misrepresented as verbatim copies of the source code.
THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS"
WITHOUT EXPRESSED OR IMPLIED WARRANTY INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR OTHER PARTY WHO MAY
MODIFY AND/OR REDISTRIBUTE THE SOFTWARE UNDER THE TERMS OF THIS LICENSE
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, LOSS OF DATA OR DATA BECOMING INACCURATE
OR LOSS OF PROFIT OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF
THE USE OR INABILITY TO USE THE SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
=========================================================================*/
#include "vtkMNITransformWriter.h"
#include "vtkObjectFactory.h"
#include "vtkMath.h"
#include "vtkImageData.h"
#include "vtkPointData.h"
#include "vtkMINCImageAttributes.h"
#include "vtkMINCImageWriter.h"
#include "vtkMINC.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkCollection.h"
#include "vtkTransform.h"
#include "vtkHomogeneousTransform.h"
#include "vtkGeneralTransform.h"
#include "vtkThinPlateSplineTransform.h"
#include "vtkGridTransform.h"
#include "vtkDoubleArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkPoints.h"
#include <ctime>
#include <cctype>
#include <cstdio>
#include <stack>
#include <vtksys/SystemTools.hxx>
//--------------------------------------------------------------------------
vtkStandardNewMacro(vtkMNITransformWriter);
//-------------------------------------------------------------------------
vtkMNITransformWriter::vtkMNITransformWriter()
{
this->FileName = 0;
this->Transform = 0;
this->Transforms = vtkCollection::New();
this->Comments = 0;
}
//-------------------------------------------------------------------------
vtkMNITransformWriter::~vtkMNITransformWriter()
{
if (this->Transforms)
{
this->Transforms->Delete();
}
if (this->Transform)
{
this->Transform->Delete();
}
delete [] this->FileName;
delete [] this->Comments;
}
//-------------------------------------------------------------------------
void vtkMNITransformWriter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "FileName: "
<< (this->FileName ? this->FileName : "none") << "\n";
os << indent << "Transform: " << this->Transform << "\n";
if (this->Transform)
{
this->Transform->PrintSelf(os, indent.GetNextIndent());
}
os << indent << "NumberOfTransforms: "
<< this->Transforms->GetNumberOfItems() << "\n";
os << indent << "Comments: "
<< (this->Comments ? this->Comments : "none") << "\n";
}
//-------------------------------------------------------------------------
int vtkMNITransformWriter::WriteLinearTransform(
ostream &outfile, vtkHomogeneousTransform *transform)
{
vtkMatrix4x4 *matrix = transform->GetMatrix();
if (matrix->GetElement(3,0) != 0.0 ||
matrix->GetElement(3,1) != 0.0 ||
matrix->GetElement(3,2) != 0.0 ||
matrix->GetElement(3,3) != 1.0)
{
vtkErrorMacro("WriteLinearTransform: The transform is not linear");
return 0;
}
outfile << "Linear_Transform =";
char text[256];
for (int i = 0; i < 3; i++)
{
outfile << "\n";
sprintf(text, " %.15g %.15g %.15g %.15g",
matrix->GetElement(i, 0),
matrix->GetElement(i, 1),
matrix->GetElement(i, 2),
matrix->GetElement(i, 3));
outfile << text;
}
outfile << ";\n";
return 1;
}
//-------------------------------------------------------------------------
int vtkMNITransformWriter::WriteThinPlateSplineTransform(
ostream &outfile, vtkThinPlateSplineTransform *transform)
{
// Write the inverse flag if necessary
if (transform->GetInverseFlag())
{
outfile << "Invert_Flag = True;\n";
}
// Get the landmarks
vtkPoints *source = transform->GetSourceLandmarks();
vtkPoints *target = transform->GetTargetLandmarks();
int n = source->GetNumberOfPoints();
if (target->GetNumberOfPoints() != n)
{
// An error will be printed out by the transform Update
return 0;
}
// Find the dimensionality of the transform
int i, j, k;
int ndim = 1;
for (i = 0; i < n; i++)
{
double p1[3], p2[3];
source->GetPoint(i, p1);
target->GetPoint(i, p2);
if (ndim == 1)
{
if (p1[1] != 0.0 || p2[1] != 0.0)
{
ndim = 2;
}
if (ndim == 2)
{
if (p1[2] != 0.0 || p2[2] != 0.0)
{
ndim = 3;
break;
}
}
}
}
// Make sure the dimensionality is correct
if (ndim == 1)
{
vtkErrorMacro("Thin plate spline points are co-linear!");
return 0;
}
if (ndim == 2 && transform->GetBasis() != VTK_RBF_R2LOGR)
{
vtkErrorMacro("Spline dimensionality is 2, but RBF is not R2LogR!");
return 0;
}
if (ndim == 3 && transform->GetBasis() != VTK_RBF_R)
{
vtkErrorMacro("Spline dimensionality is 3, but RBF is not R!");
return 0;
}
// Write out the number of dimensions
outfile << "Number_Dimensions = " << ndim << ";\n";
// Write out the points
outfile << "Points =";
for (i = 0; i < n; i++)
{
double p[3];
source->GetPoint(i, p);
outfile << "\n";
for (j = 0; j < ndim; j++)
{
char text[64];
sprintf(text, " %.15g", p[j]);
outfile << text;
}
}
outfile << ";\n";
// Create two matrices
int msize = n + ndim + 1;
double **X = new double *[ndim];
double **L = new double *[msize];
int storagelen = ndim*msize + msize*msize;
double *storage = new double[storagelen];
for (i = 0; i < storagelen; i++)
{
storage[i] = 0.0;
}
// Create the X and L matrices
for (i = 0; i < ndim; i++)
{
X[i] = &storage[i*msize];
}
for (i = 0; i < msize; i++)
{
L[i] = &storage[ndim*msize + i*msize];
}
// Fill in L matrix
for (i = 0; i < n; i++)
{
double p[3];
source->GetPoint(i, p);
L[n][i] = L[i][n] = 1.0;
for (k = 0; k < ndim; k++)
{
L[n + k + 1][i] = L[i][n + k + 1] = p[k];
}
for (j = 0; j < i; j++)
{
double p1[3];
source->GetPoint(j, p1);
double r = 0.0;
for (k = 0; k < ndim; k++)
{
r += (p[k] - p1[k])*(p[k] - p1[k]);
}
r = sqrt(r);
if (ndim == 2)
{
r = r*r*log(r);
}
L[i][j] = L[j][i] = r;
}
}
// Fill in X matrix
for (i = 0; i < n; i++)
{
double *p = target->GetPoint(i);
for (k = 0; k < ndim; k++)
{
X[k][i] = p[k];
}
}
// Solve to make X into the thin-plate spline matrix
int *pivots = new int[msize];
double *tmpstore = new double[msize];
vtkMath::LUFactorLinearSystem(L, pivots, msize, tmpstore);
for (i = 0; i < ndim; i++)
{
vtkMath::LUSolveLinearSystem(L, pivots, X[i], msize);
}
delete [] tmpstore;
delete [] pivots;
// Write out the matrix as "Displacements"
outfile << "Displacements =";
for (i = 0; i < msize; i++)
{
outfile << "\n";
for (j = 0; j < ndim; j++)
{
char text[64];
sprintf(text, " %.15g", X[j][i]);
outfile << text;
}
}
outfile << ";\n";
delete [] storage;
delete [] L;
delete [] X;
return 1;
}
//-------------------------------------------------------------------------
int vtkMNITransformWriter::WriteGridTransform(
ostream &outfile, vtkGridTransform *transform)
{
// Write the inverse flag if necessary
if (transform->GetInverseFlag())
{
outfile << "Invert_Flag = True;\n";
}
// Split FileName into directory and filename
std::vector<std::string> xfmpath;
vtksys::SystemTools::SplitPath(this->FileName, xfmpath);
if (xfmpath.size() < 1)
{
vtkErrorMacro("Can't split filename " << this->FileName);
return 0;
}
// Replace the ".xfm" extension of the filename with "_grid.mnc"
size_t i = xfmpath.size() - 1;
std::string filename =
vtksys::SystemTools::GetFilenameWithoutLastExtension(xfmpath[i]);
filename.append("_grid.mnc");
xfmpath[i] = filename;
// Write the minc filename into the .xfm file
outfile << "Displacement_Volume = " << filename << ";\n";
// Use the full path to write the minc file
vtkMINCImageWriter *writer = vtkMINCImageWriter::New();
writer->SetFileName(vtksys::SystemTools::JoinPath(xfmpath).c_str());
writer->SetInputData(transform->GetDisplacementGrid());
if (transform->GetDisplacementShift() != 0.0 ||
transform->GetDisplacementScale() != 1.0)
{
writer->SetRescaleIntercept(transform->GetDisplacementShift());
writer->SetRescaleSlope(transform->GetDisplacementScale());
}
// Write the file
writer->Write();
writer->Delete();
return 1;
}
//-------------------------------------------------------------------------
int vtkMNITransformWriter::WriteTransform(
ostream &outfile, vtkAbstractTransform *transform)
{
outfile << "Transform_Type = ";
if (transform->IsA("vtkHomogeneousTransform"))
{
outfile << "Linear;\n";
return this->WriteLinearTransform(
outfile, (vtkHomogeneousTransform *)transform);
}
else if (transform->IsA("vtkThinPlateSplineTransform"))
{
outfile << "Thin_Plate_Spline_Transform;\n";
return this->WriteThinPlateSplineTransform(
outfile, (vtkThinPlateSplineTransform *)transform);
}
else if (transform->IsA("vtkGridTransform"))
{
outfile << "Grid_Transform;\n";
return this->WriteGridTransform(
outfile, (vtkGridTransform *)transform);
}
vtkErrorMacro("Unsupported transform type "
<< transform->GetClassName());
return 0;
}
//-------------------------------------------------------------------------
int vtkMNITransformWriter::WriteFile()
{
// Check that a transform has been set.
if (!this->Transform)
{
vtkErrorMacro("WriteFile: No input transform has been set.");
return 0;
}
// Check that the file name has been set.
if (!this->FileName)
{
vtkErrorMacro("WriteFile: No file name has been set.");
return 0;
}
// Open the file.
ofstream outfile(this->FileName, ios::out);
if (outfile.fail())
{
vtkErrorMacro("WriteFile: Can't create the file " << this->FileName);
return 0;
}
// Write the header
outfile << "MNI Transform File\n";
// Get the local time and write as first comment line
char buf[1024];
time_t t;
time(&t);
strftime(buf, sizeof(buf), "%Y:%m:%d %H:%M:%S", localtime(&t));
outfile << "% Creation time: " << buf << "\n";
// Write user comments
if (this->Comments)
{
char *cp = this->Comments;
while (*cp)
{
if (*cp != '%')
{
outfile << "% ";
}
while (*cp && *cp != '\n')
{
if (isprint(*cp) || *cp == '\t')
{
outfile << *cp;
}
cp++;
}
outfile << "\n";
if (*cp == '\n')
{
cp++;
}
}
}
// Add a blank line
outfile << "\n";
// Push the transforms onto the stack in reverse order
std::stack<vtkAbstractTransform *> tstack;
int i = this->Transforms->GetNumberOfItems();
while (i > 0)
{
tstack.push(
((vtkAbstractTransform *)this->Transforms->GetItemAsObject(--i)));
}
tstack.push(this->Transform);
// Write out all the transforms on the stack
int status = 1;
while (status != 0 && !tstack.empty())
{
vtkAbstractTransform *transform = tstack.top();
tstack.pop();
if (transform->IsA("vtkGeneralTransform"))
{
// Decompose general transforms
vtkGeneralTransform *gtrans = (vtkGeneralTransform *)transform;
int n = gtrans->GetNumberOfConcatenatedTransforms();
while (n > 0)
{
tstack.push(gtrans->GetConcatenatedTransform(--n));
}
}
else
{
// Write all other kinds of transforms
status = this->WriteTransform(outfile, transform);
}
}
outfile.close();
if (status == 0)
{
// delete file
}
return status;
}
//-------------------------------------------------------------------------
int vtkMNITransformWriter::ProcessRequest(vtkInformation *request,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
if (request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()))
{
if (this->Transform)
{
this->Transform->Update();
}
int n = this->Transforms->GetNumberOfItems();
for (int i = 0; i < n; i++)
{
((vtkAbstractTransform *)this->Transforms->GetItemAsObject(i))
->Update();
}
return this->WriteFile();
}
return this->Superclass::ProcessRequest(request, inputVector, outputVector);
}
//-------------------------------------------------------------------------
void vtkMNITransformWriter::Write()
{
this->Modified();
this->Update();
}
//-------------------------------------------------------------------------
int vtkMNITransformWriter::GetNumberOfTransforms()
{
if (this->Transform == 0)
{
return 0;
}
return (1 + this->Transforms->GetNumberOfItems());
}
//-------------------------------------------------------------------------
void vtkMNITransformWriter::SetTransform(vtkAbstractTransform *transform)
{
if (transform == this->Transform)
{
return;
}
if (this->Transform != 0)
{
this->Transform->Delete();
}
if (transform != 0)
{
transform->Register(this);
}
this->Transform = transform;
this->Transforms->RemoveAllItems();
this->Modified();
}
//-------------------------------------------------------------------------
void vtkMNITransformWriter::AddTransform(vtkAbstractTransform *transform)
{
if (transform == 0)
{
return;
}
if (this->Transform == 0)
{
this->SetTransform(transform);
}
else
{
this->Transforms->AddItem(transform);
this->Modified();
}
}
|