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
|
/*****************************************************************************
* $CAMITK_LICENCE_BEGIN$
*
* CamiTK - Computer Assisted Medical Intervention ToolKit
* (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
*
* Visit http://camitk.imag.fr for more information
*
* This file is part of CamiTK.
*
* CamiTK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* CamiTK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with CamiTK. If not, see <http://www.gnu.org/licenses/>.
*
* $CAMITK_LICENCE_END$
****************************************************************************/
#include "ContourWidget.h"
#include "ContourWidgetVtkCommand.h"
// -- Application --
#include <Application.h>
#include <InteractiveSliceViewer.h>
#include <Component.h>
#include <MeshComponent.h>
#include <ImageComponent.h>
#include <SingleImageComponent.h>
#include <Transformation.h>
#include <TransformationManager.h>
#include <Log.h>
#include <Property.h>
#include <RendererWidget.h>
#include <ActionWidget.h>
// -- vtk stuff --
// disable warning generated by clang about the surrounded headers
#include <CamiTKDisableWarnings>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderWindow.h>
#include <vtkOrientedGlyphContourRepresentation.h>
#include <vtkWidgetEventTranslator.h>
#include <vtkEvent.h>
#include <vtkProperty.h>
#include <CamiTKReEnableWarnings>
#include <vtkContourWidget.h>
#include <vtkPolyData.h>
//-- Qt
#include <QBoxLayout>
#include <QFrame>
#include <QVector3D>
#include <iostream>
using namespace camitk;
// --------------- constructor ---------------
ContourWidget::ContourWidget(ActionExtension* extension) : Action(extension) {
// Setting name, description and input component
setName("Contour Widget");
setDescription(R"(<p>Add a VTK Contour widget in a 2D viewer to interactively define a region contour. The contour follows the selected slice.</p>
<p>First select the 2D viewer and then click <tt>Apply</tt> to start the contour creation:</p>
<ul>
<li>Click Apply and then left click in the chosen viewer to add the first contour node</li>
<li>Left Click: Add/select a point</li>
<li>Right Click: Add final point</li>
<li>Middle Click: Translate the contour</li>
<li>Close Contour Widget: Join the start and end handles interactively</li>
<li><tt>Delete Contour Widget</tt> button: Delete the current contour widget. This will allow you to start again from scratch in any viewer you like. It will detach the generated mesh component and leave it in its current state without deleting it. <b>Note:</b> it is not possible to re-attach it later.</li>
<li><tt>Duplicate Contour Widget</tt>Same as <tt>Delete Contour Widget</tt> but will create a new contour and mesh component from the current contour widget shape. This can be useful to use the current contour as the initialization for the next slice. Once the contour is duplicate, change the slice to move it to the next image slice</li>
</ul>
<p>You may change the color and size an any time, click <tt>Apply</tt> to update the contour. You cannot change the viewer until you click on <tt>Delete Contour Widget</tt> (or close the generated Mesh Component).</p>)");
setComponentClassName("ImageComponent");
// Setting classification family and tags
setFamily("Tutorial");
addTag("Demo");
addTag("Segmentation");
addTag("2D Interaction");
addTag("VTK Widget");
Property* viewerProperty = new Property("Viewer", 0, "The viewer in which the contour is going to be created", "");
viewerProperty->setEnumTypeName("ViewerList");
// add strings to populate the GUI
// axial = 0, coronal = 1, sagittal = 2
viewerProperty->setAttribute("enumNames", getViewerNameList());
addParameter(viewerProperty);
addParameter(new Property("Contour Color", QColor(250.0, 150.0, 50.0), tr("Color of the contour (default is orange)"), ""));
addParameter(new Property("Line Width", 2.0, tr("Contour line width"), ""));
Property* nbOfPointsProperty = new Property("Number Of Points", 0, "Number of points in the current contour (updated automatically when the contour is interactively modified).", "");
nbOfPointsProperty->setReadOnly(true);
addParameter(nbOfPointsProperty);
contourWidget = nullptr;
contourWidgetCommand = nullptr;
frontPlanePlacer = nullptr;
selectedViewer = -1;
//-- widget lazy instantiation
myWidget = nullptr;
//-- currently selected image
currentImage = nullptr;
currentMesh = nullptr;
}
// --------------- getWidget ---------------
QWidget* ContourWidget::getWidget() {
// update image
ImageComponent* selectedImage = dynamic_cast<ImageComponent*>(getTargets().last());
// check if the current image is still the same
if (selectedImage != currentImage) {
// change contour
deleteContour();
// update image
currentImage = selectedImage;
}
// create widget
if (myWidget == nullptr) {
//-- the frame
myWidget = new QFrame();
myWidget->setFrameShape(QFrame::StyledPanel);
myWidget->setFrameShadow(QFrame::Sunken);
myWidget->setLineWidth(3);
//-- the vertical layout, put every GUI elements in it
auto* informationFrameLayout = new QVBoxLayout();
// add the default action widget
informationFrameLayout->addWidget(Action::getWidget());
// add two other specific actions
QPushButton* closeContour = new QPushButton("Close Contour Widget");
informationFrameLayout->addWidget(closeContour);
QObject::connect(closeContour, SIGNAL(released()), this, SLOT(closeContour()));
QPushButton* deleteContour = new QPushButton("Delete Contour Widget");
deleteContour->setWhatsThis("Delete the current contour widget.<br/>This will allow you to start again from scratch in the viewer you like.<br/>It will detach the generated mesh component and leave it in its current state.<br/><b>Note:</b> it is not possible to re-attach it later.");
deleteContour->setToolTip("Delete the current contour widget.<br/>This will allow you to start again from scratch in the viewer you like.<br/>It will detach the generated mesh component and leave it in its current state.<br/><b>Note:</b> it is not possible to re-attach it later.");
informationFrameLayout->addWidget(deleteContour);
QObject::connect(deleteContour, SIGNAL(released()), this, SLOT(deleteContour()));
QPushButton* duplicateContour = new QPushButton("Duplicate Contour Widget");
duplicateContour->setWhatsThis("Same as \"Delete Contour Widget\" but will create a new contour and mesh component from the current contour widget shape.<br/>This can be useful to use the current contour as the initialization for the next slice.");
duplicateContour->setToolTip("Same as \"Delete Contour Widget\" but will create a new contour and mesh component from the current contour widget shape.<br/>This can be useful to use the current contour as the initialization for the next slice.");
informationFrameLayout->addWidget(duplicateContour);
QObject::connect(duplicateContour, SIGNAL(released()), this, SLOT(duplicateContour()));
//-- set the layout for the action widget
myWidget->setLayout(informationFrameLayout);
}
return myWidget;
}
// --------------- apply ---------------
Action::ApplyStatus ContourWidget::apply() {
//-- update the contour
if (contourWidget == nullptr) {
if (!initContour()) {
return ABORTED;
}
}
//-- create/update the transformed mesh
if (currentMesh == nullptr) {
// create mesh for the first time
initMesh();
}
update();
return SUCCESS;
}
// --------------- initContour ---------------
bool ContourWidget::initContour() {
// start from scratch
deleteContour();
//-- set the viewer and interactor depending on the viewer chosen by the user
selectedViewer = getParameterValue("Viewer").toInt();
QString selectedViewerName = getViewerName();
InteractiveSliceViewer* selectedInteractiveViewer = dynamic_cast<InteractiveSliceViewer*>(Application::getViewer(selectedViewerName));
if (selectedInteractiveViewer == nullptr) {
CAMITK_ERROR(tr("Cannot find \"%1\". This viewer is mandatory for creating a 2D contour.").arg(selectedViewerName))
selectedViewer = -1;
return false;
}
vtkRenderWindowInteractor* interactor = selectedInteractiveViewer->getRendererWidget()->getInteractor();
//-- create contour
contourWidget = vtkSmartPointer<vtkContourWidget>::New();
contourWidget->SetInteractor(interactor);
//-- create 3D representation either from scratch or from the given polydata
contourWidget->EnabledOn();
contourWidget->CreateDefaultRepresentation();
contourWidget->FollowCursorOn();
//-- add the callback
contourWidgetCommand = new ContourWidgetVtkCommand(this);
contourWidget->AddObserver(vtkCommand::EndInteractionEvent, contourWidgetCommand);
vtkSmartPointer<vtkOrientedGlyphContourRepresentation> contourRep = vtkOrientedGlyphContourRepresentation::SafeDownCast(contourWidget->GetRepresentation());
frontPlanePlacer = vtkSmartPointer<vtkBoundedPlanePointPlacer>::New();
contourRep->SetPointPlacer(frontPlanePlacer);
// set the displacement plane
switch (selectedViewer) {
case 1:
// Coronal is y plane
frontPlanePlacer->SetProjectionNormalToYAxis();
break;
case 2:
// Sagittal is x plane
frontPlanePlacer->SetProjectionNormalToXAxis();
break;
case 0:
default:
// Axial and default is z
frontPlanePlacer->SetProjectionNormalToZAxis();
break;
}
// connect the viewer selection changed
connect(selectedInteractiveViewer, SIGNAL(selectionChanged()), this, SLOT(update()));
// once the contour is set, the property should be read only until the contour is deleted
// although this has no effect as the ObjectController cannot produce read only enum GUI
getProperty("Viewer")->setReadOnly(true);
getProperty("Viewer")->setAttribute("enumNames", { selectedInteractiveViewer->getName() });
getProperty("Viewer")->setDescription(QString("%1 was selected to create the current contour. Please click on Restart to create a new contour in another viewer.").arg(selectedInteractiveViewer->getName()));
// refresh all viewers
refreshApplication();
return true;
}
// --------------- updateContourAndMesh ---------------
void ContourWidget::updateContourAndMesh() {
// the contour is defined in the image data frame and is positioned in 3D
// by a translation that depends on the viewer and selected slice
updateTransformation();
// change color of the VTK widget representation and current mesh using the current user choice
QColor contourColor = property("Contour Color").value<QColor>();
auto contourRep = vtkOrientedGlyphContourRepresentation::SafeDownCast(contourWidget->GetRepresentation());
contourRep->GetLinesProperty()->SetColor(contourColor.redF(), contourColor.greenF(), contourColor.blueF());
// Use white vertex which is more visible
contourRep->GetActiveProperty()->SetColor(1.0, 1.0, 1.0); // active handle
contourRep->GetProperty()->SetColor(1.0, 1.0, 1.0); // passive handle
// change line width of the contour widget
float lineWidth = property("Line Width").toFloat();
contourRep->GetLinesProperty()->SetLineWidth(lineWidth);
contourRep->GetProperty()->SetPointSize(lineWidth * 2); // force point size to double line size to make them more visible even when contour is greenish
// update contour after forcing the computation of the new mesh
contourRep->BuildRepresentation(); // same effect as: contourWidget->Render();
currentMesh->setPointSet(contourRep->GetContourRepresentationAsPolyData());
// update mesh color 3D actor color
currentMesh->setColor(contourColor.redF(), contourColor.greenF(), contourColor.blueF());
// update mesh 3D actor line width
if (currentMesh->getActor(InterfaceGeometry::Surface) != nullptr) {
currentMesh->getActor(InterfaceGeometry::Surface)->GetProperty()->SetLineWidth(lineWidth);
}
}
// --------------- deleteContour ---------------
void ContourWidget::deleteContour() {
// if already present reset observers and start from scratch
if (contourWidget != nullptr) {
contourWidget->RemoveObserver(contourWidgetCommand);
contourWidget->Off();
contourWidget = nullptr;
contourWidgetCommand = nullptr;
frontPlanePlacer = nullptr;
currentMesh = nullptr;
// disconnect
disconnect(Application::getViewer(getViewerName()), SIGNAL(selectionChanged()), this, SLOT(update()));
selectedViewer = -1;
// release viewer property
getProperty("Viewer")->setReadOnly(false);
getProperty("Viewer")->setAttribute("enumNames", getViewerNameList());
getProperty("Viewer")->setDescription("The viewer in which the contour is going to be created");
dynamic_cast<camitk::ActionWidget*>(Action::getWidget())->update();
// refresh all viewers
refreshApplication();
}
}
// --------------- initMesh ---------------
void ContourWidget::initMesh() {
QString meshName = currentImage->getName();
switch (selectedViewer) {
case 1:
meshName += " Coronal " + QString::number(currentImage->getCoronalSlices()->getSlice());
break;
case 2:
meshName += " Sagittal " + QString::number(currentImage->getSagittalSlices()->getSlice());
break;
case 0:
default:
meshName += " Axial " + QString::number(currentImage->getAxialSlices()->getSlice());
break;
}
// get vtkPointSet from the contour output to crate the new mesh component
vtkSmartPointer<vtkOrientedGlyphContourRepresentation> contourRep = vtkOrientedGlyphContourRepresentation::SafeDownCast(contourWidget->GetRepresentation());
currentMesh = new MeshComponent(contourRep->GetContourRepresentationAsPolyData(), meshName);
// the mesh is defined directly to the data image frame as the contour widget is drawn in
// the 2D viewer, i.e. the data image data
currentMesh->setFrame(TransformationManager::getFrameOfReferenceOwnership(currentImage->getDataFrame()));
// Note : this can also be accomplished by creating an identity transformation in the
// transformation information system that goes from data image frame to mesh frame:
// TransformationManager::addTransformation(currentImage->getDataFrame(), currentMesh->getFrame());
// This identity transform will place the mesh at the same place as the data image frame
// and therefore placing it as if it was defined directly in the data image frame.
// TODO When saving a mesh on its own (not in a camitk workspace), should they be saved
// directly in the world frame (as no mesh file format have any concept of transformation)?
// make sure the contour will be deleted if the mesh component or image component are closed by the user
connect(currentMesh, SIGNAL(destroyed()), this, SLOT(deleteContour()));
connect(currentImage, SIGNAL(destroyed()), this, SLOT(deleteContour()));
}
// --------------- updateTransformation ---------------
void ContourWidget::updateTransformation() {
// The transformation depends on
// - the slice plane
// - the slice id
// The transformation is required as the contour is a widget drawn in the normal plane
// of the current 2D viewer plane (z=0 for axial, y=0 of the coronal, x=0 of the sagittal).
SingleImageComponent* sliceComponent = nullptr;
// offset factor to set the translation in the middle of the current slice
// As camera is facing +z in axial, +y in coronal but -x in sagittal it can be either +0.5 or -0.5
double offsetFactor;
// index of the dimension of the translation
// 0 = sagittal (x is the normal), 1 = coronal (y is the normal) and 2 = axial (z is the normal)
int orientationIndex = 0;
switch (selectedViewer) {
case 2:
orientationIndex = 0;
sliceComponent = currentImage->getSagittalSlices();
// for sagittal move toward z
offsetFactor = 1.0;
break;
case 1:
// for coronal and axial move backward z
offsetFactor = -1.0;
sliceComponent = currentImage->getCoronalSlices();
orientationIndex = 1;
break;
case 0:
default:
orientationIndex = 2;
// for coronal and axial move backward z
offsetFactor = -1.0;
sliceComponent = currentImage->getAxialSlices();
}
// image dimension
double voxelSize[3];
currentImage->getImageData()->GetSpacing(voxelSize);
/// slice index + 1/2 slice offset
double sliceId = sliceComponent->getSlice() + offsetFactor * 0.5;
double translation = sliceId * voxelSize[orientationIndex];
// if needed ad a tenth voxelsize offset (slightly out of plane shift for proper visualization)
// translation += offsetFactor * voxelSize[orientationIndex] / 10.0;
// finally set the translation in the placer and force an update
frontPlanePlacer->SetProjectionPosition(translation);
frontPlanePlacer->UpdateInternalState();
}
// --------------- getViewerName ---------------
QString ContourWidget::getViewerName() {
switch (selectedViewer) {
case 1:
return "Coronal Viewer";
break;
case 2:
return "Sagittal Viewer";
break;
case 0:
default:
return "Axial Viewer";
break;
}
}
// --------------- getViewerNameList ---------------
QStringList ContourWidget::getViewerNameList() {
return QStringList({ "Axial Viewer", "Coronal Viewer", "Sagittal Viewer" });
}
// --------------- closeContour ---------------
void ContourWidget::closeContour() {
contourWidget->CloseLoop();
update();
}
// --------------- update ---------------
void ContourWidget::update() {
// update contour widget and mesh
if (contourWidget != nullptr && currentMesh != nullptr) {
updateContourAndMesh();
}
// update action's widget from modified property (this is not the "usual" way, normally
// the user modify some property in the widget and the action gets the value to do
// something. In this case, the action's property is modified by some external
// mechanism (not the user), e.g. here the vtContourWidget, therefore the action's widget has
// to be updated
dynamic_cast<camitk::ActionWidget*>(Action::getWidget())->update();
// refresh all viewers
refreshApplication();
}
// --------------- duplicateContour ---------------
void ContourWidget::duplicateContour() {
if (contourWidget != nullptr) {
// backup the poly data without the (sp)line interpolation
auto contourRep = vtkOrientedGlyphContourRepresentation::SafeDownCast(contourWidget->GetRepresentation());
vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
contourRep->GetNodePolyData(polyData);
deleteContour();
// change current color
QColor contourColor = property("Contour Color").value<QColor>();
setParameterValue("Contour Color", QColor::fromHsv((contourColor.hue() + 45) % 360, contourColor.saturation(), contourColor.value()));
initContour();
// initialize the contour with the previous one
contourWidget->Initialize(polyData);
initMesh();
update();
refreshApplication();
}
}
|