-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaxialslicewidget.cpp
1656 lines (1349 loc) · 61.5 KB
/
axialslicewidget.cpp
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "axialslicewidget.h"
#include "commands.h"
AxialSliceWidget::AxialSliceWidget(QWidget *parent) : QOpenGLWidget(parent),
displayType(SliceDisplayType::FatOnly), fatImage(NULL), waterImage(NULL), tracingData(NULL),
tracingLayerColors({ Qt::blue, Qt::darkCyan, Qt::cyan, Qt::magenta, Qt::yellow, Qt::green }), mouseCommand(NULL),
slicePrimTexture(0), sliceSecdTexture(0),
location(0, 0, 0, 0), locationLabel(NULL), primColorMap(ColorMap::Gray), primOpacity(1.0f), secdColorMap(ColorMap::Gray), secdOpacity(1.0f),
brightness(0.0f), brightnessThreshold(0.0f), contrast(1.0f), tracingLayer(TracingLayer::EAT), drawMode(DrawMode::Points), eraserBrushWidth(1),
startDraw(false), startPan(false), moveID(CommandID::AxialMove),
frameCount(0), fps(0.0f)
{
this->tracingLayerVisible.fill(true);
this->traceTextureInit.fill(false);
}
void AxialSliceWidget::setup(NIFTImage *fat, NIFTImage *water, TracingData *tracing)
{
if (!fat || !water || !tracing)
{
qDebug() << "Invalid fat image, water image or tracing data in setup: " << fat << water << tracing;
return;
}
fatImage = fat;
waterImage = water;
tracingData = tracing;
location = QVector4D(0, 0, 0, 0);
}
bool AxialSliceWidget::isLoaded() const
{
return (fatImage->isLoaded() && waterImage->isLoaded());
}
void AxialSliceWidget::imageLoaded()
{
sliceTexturePrimInit = false;
sliceTextureSecdInit = false;
this->traceTextureInit.fill(false);
dirty |= Dirty::Slice | Dirty::TracesAll;
update();
}
void AxialSliceWidget::readSettings(QSettings &settings)
{
settings.beginGroup("axialSliceWidget");
brightness = settings.value("brightness", 0.0f).toFloat();
brightnessThreshold = settings.value("brightnessThreshold", 0.0f).toFloat();
contrast = settings.value("contrast", 1.0f).toFloat();
primColorMap = (ColorMap)settings.value("primColorMap", (int)ColorMap::Gray).toInt();
primOpacity = settings.value("primOpacity", 1.0f).toFloat();
secdColorMap = (ColorMap)settings.value("secdColorMap", (int)ColorMap::Gray).toInt();
secdOpacity = settings.value("secdOpacity", 1.0f).toFloat();
displayType = (SliceDisplayType)settings.value("displayType", (int)SliceDisplayType::FatOnly).toInt();
int size = settings.beginReadArray("tracingLayerVisible");
for (int i = 0; i < size; ++i)
{
settings.setArrayIndex(i);
tracingLayerVisible[i] = settings.value("visible", true).toBool();
}
settings.endArray();
drawMode = (DrawMode)settings.value("drawMode", (int)DrawMode::Points).toInt();
eraserBrushWidth = settings.value("eraserBrushWidth", 1).toInt();
settings.endGroup();
}
void AxialSliceWidget::writeSettings(QSettings &settings)
{
settings.beginGroup("axialSliceWidget");
settings.setValue("brightness", brightness);
settings.setValue("brightnessThreshold", brightnessThreshold);
settings.setValue("contrast", contrast);
settings.setValue("primColorMap", (int)primColorMap);
settings.setValue("primOpacity", primOpacity);
settings.setValue("secdColorMap", (int)secdColorMap);
settings.setValue("secdOpacity", secdOpacity);
settings.setValue("displayType", (int)displayType);
settings.beginWriteArray("tracingLayerVisible");
for (size_t i = 0; i < tracingLayerVisible.size(); ++i)
{
settings.setArrayIndex((int)i);
settings.setValue("visible", tracingLayerVisible[i]);
}
settings.endArray();
settings.setValue("drawMode", (int)drawMode);
settings.setValue("eraserBrushWidth", eraserBrushWidth);
settings.endGroup();
}
void AxialSliceWidget::setLocation(QVector4D location)
{
// If there is no fat or water image currently loaded then return with doing nothing.
if (!isLoaded())
return;
QVector4D transformedLocation = transformLocation(location);
QVector4D delta = transformedLocation - this->location;
this->location = transformedLocation;
// If Z value changed, then update the texture
if (delta.z())
dirty |= (Dirty::Slice | Dirty::TracesAll);
// Update location label
if (locationLabel)
locationLabel->setText(QObject::tr("Location: (%1, %2, %3)").arg(this->location.x()).arg(this->location.y()).arg(this->location.z()));
update();
}
QVector4D AxialSliceWidget::getLocation() const
{
return location;
}
QVector4D AxialSliceWidget::transformLocation(QVector4D location) const
{
// This function returns a QVector4D that replaces Location::NoChange's from location variable with actual location value
QVector4D temp(location.x() == Location::NoChange, location.y() == Location::NoChange, location.z() == Location::NoChange, location.w() == Location::NoChange);
QVector4D notTemp = QVector4D(1.0f, 1.0f, 1.0f, 1.0f) - temp;
return (location * notTemp) + (this->location * temp);
}
QLabel *AxialSliceWidget::getLocationLabel() const
{
return locationLabel;
}
void AxialSliceWidget::setLocationLabel(QLabel *label)
{
locationLabel = label;
}
SliceDisplayType AxialSliceWidget::getDisplayType() const
{
return displayType;
}
void AxialSliceWidget::setDisplayType(SliceDisplayType type)
{
// If the display type is out of the acceptable range, then do nothing
if (type < SliceDisplayType::FatOnly || type > SliceDisplayType::WaterFat)
{
qWarning() << "Invalid display type was specified for AxialSliceWidget: " << (int)type;
return;
}
displayType = type;
// This will recreate the texture because the display type has changed
dirty |= Dirty::Slice;
update();
}
ColorMap AxialSliceWidget::getPrimColorMap() const
{
return primColorMap;
}
void AxialSliceWidget::setPrimColorMap(ColorMap map)
{
// If the map given is out of the acceptable range, then do nothing
if (map < ColorMap::Autumn || map >= ColorMap::Count)
{
qWarning() << "Invalid primary color map was specified for AxialSliceWidget: " << (int)map;
return;
}
primColorMap = map;
// Redraw the screen because the screen colormap has changed
update();
}
float AxialSliceWidget::getPrimOpacity() const
{
return primOpacity;
}
void AxialSliceWidget::setPrimOpacity(float opacity)
{
if (opacity < 0.0f || opacity > 1.0f)
{
qWarning() << "Invalid primary opacity level was specified for AxialSliceWidget: " << opacity;
return;
}
primOpacity = opacity;
// Redraw the screen because the opacity of one of the objects changed
update();
}
ColorMap AxialSliceWidget::getSecdColorMap() const
{
return secdColorMap;
}
void AxialSliceWidget::setSecdColorMap(ColorMap map)
{
// If the map given is out of the acceptable range, then do nothing
if (map < ColorMap::Autumn || map >= ColorMap::Count)
{
qWarning() << "Invalid secondary color map was specified for AxialSliceWidget: " << (int)map;
return;
}
secdColorMap = map;
// Redraw the screen because the screen colormap has changed
update();
}
float AxialSliceWidget::getSecdOpacity() const
{
return secdOpacity;
}
void AxialSliceWidget::setSecdOpacity(float opacity)
{
if (opacity < 0.0f || opacity > 1.0f)
{
qWarning() << "Invalid secondary opacity level was specified for AxialSliceWidget: " << opacity;
return;
}
secdOpacity = opacity;
// Redraw the screen because the opacity of one of the objects changed
update();
}
float AxialSliceWidget::getBrightness() const
{
return brightness;
}
void AxialSliceWidget::setBrightness(float brightness)
{
// If the brightness is out of the acceptable range, then do nothing
if (brightness < 0.0f || brightness > 1.0f)
{
qWarning() << "Invalid brightness was specified for AxialSliceWidget: " << brightness;
return;
}
this->brightness = brightness;
// Redraw the screen because the brightness has changed
dirty |= Dirty::Slice;
update();
}
float AxialSliceWidget::getBrightnessThreshold() const
{
return brightnessThreshold;
}
void AxialSliceWidget::setBrightnessThreshold(float threshold)
{
// If the brightness is out of the acceptable range, then do nothing
if (threshold < 0.0f || threshold > 1.0f)
{
qWarning() << "Invalid brightness threshold was specified for AxialSliceWidget: " << threshold;
return;
}
this->brightnessThreshold = threshold;
// Redraw the screen because the brightness has changed
dirty |= Dirty::Slice;
update();
}
float AxialSliceWidget::getContrast() const
{
return contrast;
}
void AxialSliceWidget::setContrast(float contrast)
{
// If the contrast is out of the acceptable range, then do nothing
if (contrast < 0.0f || contrast > 1.0f)
{
qWarning() << "Invalid contrast was specified for AxialSliceWidget: " << contrast;
return;
}
this->contrast = contrast;
// Redraw the screen because the contrast has changed
dirty |= Dirty::Slice;
update();
}
DrawMode AxialSliceWidget::getDrawMode() const
{
return drawMode;
}
void AxialSliceWidget::setDrawMode(DrawMode mode)
{
drawMode = mode;
update();
}
int AxialSliceWidget::getEraserBrushWidth() const
{
return eraserBrushWidth;
}
void AxialSliceWidget::setEraserBrushWidth(int width)
{
eraserBrushWidth = width;
update();
}
TracingLayer AxialSliceWidget::getTracingLayer() const
{
return tracingLayer;
}
void AxialSliceWidget::setTracingLayer(TracingLayer layer)
{
// If the layer is out of the acceptable range, then do nothing
if (layer < TracingLayer::EAT || layer >= TracingLayer::Count)
{
qWarning() << "Invalid current tracing layer was specified for AxialSliceWidget: " << (int)layer;
return;
}
tracingLayer = layer;
}
bool AxialSliceWidget::getTracingLayerVisible(TracingLayer layer) const
{
// If the layer is out of the acceptable range, then do nothing
if (layer < TracingLayer::EAT || layer >= TracingLayer::Count)
{
qWarning() << "Invalid current tracing layer was specified for AxialSliceWidget: " << (int)layer;
return false;
}
return tracingLayerVisible[(int)layer];
}
void AxialSliceWidget::setTracingLayerVisible(TracingLayer layer, bool value)
{
// If the layer is out of the acceptable range, then do nothing
if (layer < TracingLayer::EAT || layer >= TracingLayer::Count)
{
qWarning() << "Invalid current tracing layer was specified for AxialSliceWidget: " << (int)layer;
return;
}
tracingLayerVisible[(int)layer] = value;
}
TracingLayerData &AxialSliceWidget::getTraceSlices(TracingLayer layer)
{
if (layer == TracingLayer::Count)
layer = tracingLayer;
return (*tracingData)[layer];
}
float &AxialSliceWidget::rscaling()
{
return scaling;
}
QVector3D &AxialSliceWidget::rtranslation()
{
return translation;
}
bool AxialSliceWidget::saveTracingData(QuaZip *zip)
{
const QString layerFilename[(int)TracingLayer::Count] = {"EAT.txt", "IMAT.txt", "PAAT.txt", "PAT.txt", "SCAT.txt", "VAT.txt"};
const QString timeDir = "times";
QString layerTimePath[(int)TracingLayer::Count];
// Prepend timeDir to the layer filename to store the times
for (int i = 0; i < (int)TracingLayer::Count; ++i)
layerTimePath[i] = QDir(timeDir).filePath(layerFilename[i]);
for (int i = 0; i < (int)TracingLayer::Count; ++i)
{
// Begin by saving trace points
QuaZipFile sliceFile(zip);
if (!sliceFile.open(QIODevice::WriteOnly | QIODevice::Truncate, QuaZipNewInfo(layerFilename[i])))
{
qWarning() << "Error while creating tracing data file for " << layerFilename[i];
continue;
}
QTextStream sliceStream(&sliceFile);
sliceStream << fatImage->getZDim() << endl;
const int zDim = fatImage->getZDim();
for (int z = 0; z < zDim; ++z)
{
auto &traceLayer = (*tracingData)[i];
cv::Mat slice = traceLayer.getAxialSlice(z);
cv::Mat points;
opencv::findNonZero(slice, points);
// Only sort if there are points to sort
if (points.total() > 0)
{
// Sort based on Z, then Y, then X value.
std::sort(points.begin<cv::Vec2i>(), points.end<cv::Vec2i>(), [](const cv::Vec2i &a, const cv::Vec2i &b) {
return !((a[0] >= b[0]) && (a[0] != b[0] || a[1] >= b[1]));
});
}
sliceStream << "#" << z << endl;
sliceStream << points.total() << endl;
for (size_t i = 0; i < points.total(); ++i)
{
const cv::Vec2i point = points.at<cv::Vec2i>((int)i);
sliceStream << forcepoint << (float)point[1] << " " << (float)point[0] << " " << (float)z << endl;
}
}
// Close slice file now that we are done with it
// Note: YOU CANNNOT HAVE TWO ZIP FILES OPENED AT ONCE SO BE CAREFUL
sliceFile.close();
// Save tracing time data next
QuaZipFile timeFile(zip);
if (!timeFile.open(QIODevice::WriteOnly | QIODevice::Truncate, QuaZipNewInfo(layerTimePath[i])))
{
qWarning() << "Error opening file to save time tracing data. Skipping layer: " << layerTimePath[i];
continue;
}
QTextStream timeStream(&timeFile);
timeStream << fatImage->getZDim() << endl;
for (int z = 0; z < zDim; ++z)
{
auto &traceLayer = (*tracingData)[i];
auto time = traceLayer.time[z];
auto h = std::chrono::duration_cast<std::chrono::hours>(time);
auto m = std::chrono::duration_cast<std::chrono::minutes>(time -= h);
auto s = std::chrono::duration_cast<std::chrono::seconds>(time -= m);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(time -= s);
timeStream << "#" << z << " " << h.count() << "h " << m.count() << "m " << s.count() << "s " << ms.count() << "ms" << endl;
}
}
// Set stack to clean to notify the application that no unsaved changes are present
undoStack->setClean();
return true;
}
bool AxialSliceWidget::loadTracingData(QuaZip *zip)
{
if (!isLoaded())
{
qWarning() << "Tracing data cannot be imported into an application until the correct NIFTI image is loaded first.\nPlease load the correct NIFTI file and then try again.";
return false;
}
bool hasData = false;
for (auto &layer : this->tracingData->layers)
{
if (cv::countNonZero(layer.data) > 0)
{
hasData = true;
break;
}
}
// If there is data in the fat layers and the stack is not clean, then prompt user if they are sure they want to import tracing data
// NOTE: This has the flaw that even simple settings such as changing color map and stuff will make the stack not clean.
if (hasData && !undoStack->isClean())
{
if (QMessageBox::warning((QWidget *)parent(), "Confirm Import", "Unsaved tracing data is present in this image.\nAre you sure you want to load this new tracing data and discard current changes?", QMessageBox::Yes, QMessageBox::No)
!= QMessageBox::Yes)
return false;
}
const QString layerFilename[(int)TracingLayer::Count] = {"EAT.txt", "IMAT.txt", "PAAT.txt", "PAT.txt", "SCAT.txt", "VAT.txt"};
const QString timeDir = "times";
QString layerTimePath[(int)TracingLayer::Count];
// Prepend timeDir to the layer filename to store the times
for (int i = 0; i < (int)TracingLayer::Count; ++i)
layerTimePath[i] = QDir(timeDir).filePath(layerFilename[i]);
for (int i = 0; i < (int)TracingLayer::Count; ++i)
{
// Set current file to the current layer to load
zip->setCurrentFile(layerFilename[i]);
// Begin by loading trace points
QuaZipFile sliceFile(zip);
if (!sliceFile.open(QIODevice::ReadOnly))
{
qWarning() << "Error while creating tracing data file for " << layerFilename[i];
continue;
}
QTextStream sliceStream(&sliceFile);
int zDim;
sliceStream >> zDim;
if (zDim != fatImage->getZDim())
{
qWarning() << "Number of axial slices in the data does not match the NIFTI image loaded.";
return false; // Note: Return false because the other layers should be mismatched as well
}
auto &layer = (*tracingData)[i];
// Discard previous data by setting everything to 0
layer.data.setTo(0);
for (int z = 0; z < zDim; ++z)
{
// Skip the #Z where Z is the axial slice
sliceStream.skipWhiteSpace();
sliceStream.readLine();
// Get the number of points on the slices
int numPoints = 0;
sliceStream >> numPoints;
float x, y, z_;
for (int ii = 0; ii < numPoints; ++ii)
{
sliceStream >> x >> y >> z_;
if ((z < 0 || z >= fatImage->getZDim()) || (y < 0 || y >= fatImage->getYDim()) || (x < 0 || x >= fatImage->getXDim()))
{
qWarning() << "A point specified was outside the boundary of the current NIFTI image: (" << z << "," << y << "," << x << ")";
return false;
}
layer.set(x, y, z);
}
}
// Close slice file now that we are done with it
// Note: YOU CANNOT HAVE TWO ZIP FILES OPENED AT ONCE SO BE CAREFUL
sliceFile.close();
// Load tracing time data next
// Set current file to the current time layer to load
zip->setCurrentFile(layerTimePath[i]);
QuaZipFile timeFile(zip);
if (!timeFile.open(QIODevice::ReadOnly))
{
qWarning() << "Error opening file to save time tracing data. Skipping layer: " << layerTimePath[i];
continue;
}
QTextStream timeStream(&timeFile);
timeStream >> zDim;
if (zDim != fatImage->getZDim())
{
qWarning() << "Number of axial slices in the time data does not match the NIFTI image loaded.";
return false; // Note: Return false because the other layers should be mismatched as well
}
for (int z = 0; z < zDim; ++z)
{
// Skip the #Z where Z is the axial slice
timeStream.skipWhiteSpace();
// Read timing
char dummy;
int z__;
QString str;
unsigned int h, m, s, ms;
timeStream >> dummy >> z__ >> ws >> h >> str >> ws >> m >> str >> ws >> s >> str >> ws >> ms >> str >> ws;
layer.time[z] = (std::chrono::hours(h) + std::chrono::minutes(m) + std::chrono::seconds(s) + std::chrono::milliseconds(ms));
}
}
// Clear the undoStack so that all of the tracing commands are deleted from beforehand
// This may cause unwanted commands to be deleted but it is okay
undoStack->clear();
// Update all traces textures and update screen
dirty |= Dirty::TracesAll;
update();
return true;
}
QMatrix4x4 AxialSliceWidget::getMVPMatrix() const
{
// Calculate the ModelViewProjection (MVP) matrix to transform the location of the axial slices
QMatrix4x4 modelMatrix;
// Translate the modelMatrix according to translation vector
// Then scale according to scaling factor
modelMatrix.translate(translation);
modelMatrix.scale(scaling);
return (projectionMatrix * viewMatrix * modelMatrix);
}
QMatrix4x4 AxialSliceWidget::getWindowToNIFTIMatrix(bool includeMVP) const
{
return (getNIFTIToOpenGLMatrix(includeMVP, !includeMVP).inverted() * getWindowToOpenGLMatrix(false, true));
}
QMatrix4x4 AxialSliceWidget::getWindowToOpenGLMatrix(bool includeMVP, bool flipY) const
{
QMatrix4x4 windowToOpenGLMatrix;
windowToOpenGLMatrix.translate(-1.0f, (flipY ? 1.0f : -1.0f));
windowToOpenGLMatrix.scale(2.0f / width(), (flipY ? -2.0f : 2.0f) / height());
if (includeMVP)
return (getMVPMatrix() * windowToOpenGLMatrix);
else
return windowToOpenGLMatrix;
}
QMatrix4x4 AxialSliceWidget::getNIFTIToOpenGLMatrix(bool includeMVP, bool flipY) const
{
QMatrix4x4 NIFTIToOpenGLMatrix;
NIFTIToOpenGLMatrix.translate(-1.0f, flipY ? 1.0f : -1.0f);
NIFTIToOpenGLMatrix.scale(2.0f / (fatImage->getXDim() - 1), (flipY ? -2.0f : 2.0f) / (fatImage->getYDim() - 1));
if (includeMVP)
return (getMVPMatrix() * NIFTIToOpenGLMatrix);
else
return NIFTIToOpenGLMatrix;
}
void AxialSliceWidget::setUndoStack(QUndoStack *stack)
{
undoStack = stack;
}
void AxialSliceWidget::setDirty(int bit)
{
dirty |= bit;
}
void AxialSliceWidget::resetView()
{
// Reset translation and scaling factors
translation = QVector3D(0.0f, 0.0f, 0.0f);
scaling = 1.0f;
// Update the screen
update();
}
void AxialSliceWidget::initializeGL()
{
if (!initializeOpenGLFunctions())
{
qCritical() << "Unable to initialize OpenGL functions for AxialSliceWidget";
return;
}
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Setup matrices and view options
projectionMatrix.setToIdentity();
viewMatrix.setToIdentity();
scaling = 1.0f;
translation = QVector3D(0.0f, 0.0f, 0.0f);
sliceProgram = new QOpenGLShaderProgram();
sliceProgram->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/shaders/axialslice.vert");
sliceProgram->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/shaders/axialslice.frag");
sliceProgram->link();
sliceProgram->bind();
if (!sliceProgram->log().isEmpty())
qDebug() << "Slice Program Log: " << sliceProgram->log();
glCheckError();
sliceProgram->setUniformValue("tex", 0);
sliceProgram->setUniformValue("mappingTexture", 1);
traceProgram = new QOpenGLShaderProgram();
traceProgram->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/shaders/fattraces.vert");
traceProgram->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/shaders/fattraces.frag");
traceProgram->link();
traceProgram->bind();
if (!traceProgram->log().isEmpty())
qDebug() << "Trace Program Log: " << traceProgram->log();
glCheckError();
traceProgram->setUniformValue("tex", 0);
initializeSliceView();
initializeTracing();
initializeColorMaps();
fpsTimer.start();
frameCount = 0;
}
void AxialSliceWidget::initializeSliceView()
{
// get context opengl-version
qDebug() << "----------------- AxialSliceWidget ---------------------------";
qDebug() << "Widget OpenGL: " << format().majorVersion() << "." << format().minorVersion();
qDebug() << "Context valid: " << context()->isValid();
qDebug() << "Really used OpenGL: " << context()->format().majorVersion() << "." << context()->format().minorVersion();
qDebug() << "OpenGL information: VENDOR: " << (const char*)glGetString(GL_VENDOR);
qDebug() << " RENDERDER: " << (const char*)glGetString(GL_RENDERER);
qDebug() << " VERSION: " << (const char*)glGetString(GL_VERSION);
qDebug() << " GLSL VERSION: " << (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
qDebug() << "";
sliceTexturePrimInit = false;
sliceTextureSecdInit = false;
// Setup the axial slice vertices
sliceVertices.clear();
sliceVertices.append(VertexPT(QVector3D(-1.0f, -1.0f, 0.0f), QVector2D(0.0f, 0.0f)));
sliceVertices.append(VertexPT(QVector3D(-1.0f, 1.0f, 0.0f), QVector2D(0.0f, 1.0f)));
sliceVertices.append(VertexPT(QVector3D(1.0f, -1.0f, 0.0f), QVector2D(1.0f, 0.0f)));
sliceVertices.append(VertexPT(QVector3D(1.0f, 1.0f, 0.0f), QVector2D(1.0f, 1.0f)));
// Setup the axial slice indices
sliceIndices.clear();
sliceIndices.append({ 0, 1, 2, 3});
// Generate vertex buffer for the axial slice. The sliceVertices data is uploaded to the VBO
glGenBuffers(1, &sliceVertexBuf);
glBindBuffer(GL_ARRAY_BUFFER, sliceVertexBuf);
glBufferData(GL_ARRAY_BUFFER, sliceVertices.size() * sizeof(VertexPT), sliceVertices.constData(), GL_STATIC_DRAW);
glCheckError();
// Generate index buffer for the axial slice. The sliceIndices data is uploaded to the IBO
glGenBuffers(1, &sliceIndexBuf);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sliceIndexBuf);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sliceIndices.size() * sizeof(GLushort), sliceIndices.constData(), GL_STATIC_DRAW);
glCheckError();
// Generate VAO for the axial slice vertices uploaded. Location 0 is the position and location 1 is the texture position
glGenVertexArrays(1, &sliceVertexObject);
glBindVertexArray(sliceVertexObject);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, VertexPT::PosTupleSize, GL_FLOAT, true, VertexPT::stride(), static_cast<const char *>(0) + VertexPT::posOffset());
glVertexAttribPointer(1, VertexPT::TexPosTupleSize, GL_FLOAT, true, VertexPT::stride(), static_cast<const char *>(0) + VertexPT::texPosOffset());
glCheckError();
// Generate a blank texture for the axial slice
glGenTextures(1, &this->slicePrimTexture);
glGenTextures(1, &this->sliceSecdTexture);
glCheckError();
// Release (unbind) all
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void AxialSliceWidget::initializeTracing()
{
this->traceTextureInit.fill(false);
// Setup the trace vertices
traceVertices.clear();
traceVertices.append(VertexPT(QVector3D(-1.0f, -1.0f, 0.0f), QVector2D(0.0f, 0.0f)));
traceVertices.append(VertexPT(QVector3D(-1.0f, 1.0f, 0.0f), QVector2D(0.0f, 1.0f)));
traceVertices.append(VertexPT(QVector3D(1.0f, -1.0f, 0.0f), QVector2D(1.0f, 0.0f)));
traceVertices.append(VertexPT(QVector3D(1.0f, 1.0f, 0.0f), QVector2D(1.0f, 1.0f)));
// Setup the trace indices
traceIndices.clear();
traceIndices.append({ 0, 1, 2, 3});
// Generate vertex buffer for the axial slice. The sliceVertices data is uploaded to the VBO
glGenBuffers(1, &traceVertexBuf);
glBindBuffer(GL_ARRAY_BUFFER, traceVertexBuf);
glBufferData(GL_ARRAY_BUFFER, traceVertices.size() * sizeof(VertexPT), traceVertices.constData(), GL_STATIC_DRAW);
glCheckError();
// Generate index buffer for the axial slice. The sliceIndices data is uploaded to the IBO
glGenBuffers(1, &traceIndexBuf);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, traceIndexBuf);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, traceIndices.size() * sizeof(GLushort), traceIndices.constData(), GL_STATIC_DRAW);
glCheckError();
// Generate VAO for the axial slice vertices uploaded. Location 0 is the position and location 1 is the texture position
glGenVertexArrays(1, &traceVertexObject);
glBindVertexArray(traceVertexObject);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, VertexPT::PosTupleSize, GL_FLOAT, true, VertexPT::stride(), static_cast<const char *>(0) + VertexPT::posOffset());
glVertexAttribPointer(1, VertexPT::TexPosTupleSize, GL_FLOAT, true, VertexPT::stride(), static_cast<const char *>(0) + VertexPT::texPosOffset());
glCheckError();
// Generate a blank texture for the axial slice
glGenTextures((int)TracingLayer::Count, &this->traceTextures[0]);
glCheckError();
// Release (unbind) all
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void AxialSliceWidget::initializeColorMaps()
{
// Internal format is how the data will be stored in the GPU. Format/type is how the data is represented
const GLint internalFormat = GL_RGBA32F;
const GLenum format = GL_RGBA;
const GLenum type = GL_UNSIGNED_BYTE;
// Create textures for each of the color maps
glGenTextures((GLsizei)ColorMap::Count, &this->colorMapTexture[0]);
glCheckError();
for (int i = 0; i < (int)ColorMap::Count; ++i)
{
QPixmap pixmap;
if (!pixmap.load(colorMapImageName[i]))
{
qWarning() << "Unable to load color map number " << i << " located at " << colorMapImageName[i];
continue;
}
// For simplicity, just convert the image to a 32-bit value. That way we know what the format is
QImage image = pixmap.toImage().convertToFormat(QImage::Format_RGBA8888);
if (image.height() != 1)
{
qWarning() << "Height must be 1 for color map number " << i << " located at " << colorMapImageName[i] << ": " << image.height();
continue;
}
// This is a formula to determine if a number is a power of two easily. If equal to zero, it is a power of two
if ((image.width() & (image.width() - 1)) != 0)
{
qWarning() << "Width must be power of two for color map number " << i << " located at " << colorMapImageName[i] << ": " << image.width();
continue;
}
// Bind the texture and setup the parameters for it
glBindTexture(GL_TEXTURE_1D, colorMapTexture[i]);
// These parameters say that the color value for a pixel will be chosen based on the nearest pixel value. This creates a more blocky effect
// since it will not be linearly interpolated like GL_LINEAR
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// This parameter will clamp points to [0.0, 1.0]. This means that anything above 1.0 will become 1.0
// and anything below 0.0 will become 0.0
//glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glCheckError();
glTexImage1D(GL_TEXTURE_1D, 0, internalFormat, image.width(), 0, format, type, image.bits());
glCheckError();
}
}
void AxialSliceWidget::updateTexture()
{
cv::Mat primMatrix;
cv::Mat secdMatrix;
switch (displayType)
{
case SliceDisplayType::FatOnly:
{
// Get the slice for the fat image. If the result is empty then there was an error retrieving the slice
primMatrix = fatImage->getAxialSlice(location.z(), true);
if (primMatrix.empty())
{
qWarning() << "Unable to retrieve axial slice " << location.z() << " from the fat image. Matrix returned empty.";
return;
}
// The normalize function does quite a bit here. It converts the matrix to a 32-bit float and normalizes it
// between 0.0f to 1.0f based on the min/max value. This does not affect the original 3D matrix in fatImage
cv::normalize(primMatrix.clone(), primMatrix, 0.0f, 1.0f, cv::NORM_MINMAX, CV_32FC1);
}
break;
case SliceDisplayType::WaterOnly:
{
// Get the slice for the water image. If the result is empty then there was an error retrieving the slice
primMatrix = waterImage->getAxialSlice(location.z(), true);
if (primMatrix.empty())
{
qWarning() << "Unable to retrieve axial slice " << location.z() << " from the water image. Matrix returned empty.";
return;
}
// The normalize function does quite a bit here. It converts the matrix to a 32-bit float and normalizes it
// between 0.0f to 1.0f based on the min/max value. This does not affect the original 3D matrix in waterImage
cv::normalize(primMatrix.clone(), primMatrix, 0.0f, 1.0f, cv::NORM_MINMAX, CV_32FC1);
}
break;
case SliceDisplayType::FatFraction:
{
// Get the slice for the fat/water image. If the result is empty then there was an error retrieving the slice
cv::Mat fatTemp = fatImage->getAxialSlice(location.z(), true);
cv::Mat waterTemp = waterImage->getAxialSlice(location.z(), true);
if (fatTemp.empty() || waterTemp.empty())
{
qWarning() << "Unable to retrieve axial slice " << location.z() << " from the fat or water image. Matrix returned empty.";
return;
}
// The normalize function does quite a bit here. It converts the matrix to a 32-bit float and normalizes it
// between 0.0f to 1.0f based on the min/max value. This does not affect the original 3D matrix in fatImage/waterImage
cv::normalize(fatTemp.clone(), fatTemp, 0.0f, 1.0f, cv::NORM_MINMAX, CV_32FC1);
cv::normalize(waterTemp.clone(), waterTemp, 0.0f, 1.0f, cv::NORM_MINMAX, CV_32FC1);
primMatrix = fatTemp / (fatTemp + waterTemp);
}
break;
case SliceDisplayType::WaterFraction:
{
// Get the slice for the fat/water image. If the result is empty then there was an error retrieving the slice
cv::Mat fatTemp = fatImage->getAxialSlice(location.z(), true);
cv::Mat waterTemp = waterImage->getAxialSlice(location.z(), true);
if (fatTemp.empty() || waterTemp.empty())
{
qWarning() << "Unable to retrieve axial slice " << location.z() << " from the fat or water image. Matrix returned empty.";
return;
}
// The normalize function does quite a bit here. It converts the matrix to a 32-bit float and normalizes it
// between 0.0f to 1.0f based on the min/max value. This does not affect the original 3D matrix in fatImage/waterImage
cv::normalize(fatTemp.clone(), fatTemp, 0.0f, 1.0f, cv::NORM_MINMAX, CV_32FC1);
cv::normalize(waterTemp.clone(), waterTemp, 0.0f, 1.0f, cv::NORM_MINMAX, CV_32FC1);
primMatrix = waterTemp / (fatTemp + waterTemp);
}
break;
case SliceDisplayType::FatWater:
{
// Get the slice for the fat image. If the result is empty then there was an error retrieving the slice
primMatrix = fatImage->getAxialSlice(location.z(), true);
if (primMatrix.empty())
{
qWarning() << "Unable to retrieve axial slice " << location.z() << " from the fat image. Matrix returned empty.";
return;
}
// The normalize function does quite a bit here. It converts the matrix to a 32-bit float and normalizes it
// between 0.0f to 1.0f based on the min/max value. This does not affect the original 3D matrix in fatImage
cv::normalize(primMatrix.clone(), primMatrix, 0.0f, 1.0f, cv::NORM_MINMAX, CV_32FC1);
// Get the slice for the water image. If the result is empty then there was an error retrieving the slice
// The secondary matrix is the water image in this case
secdMatrix = waterImage->getAxialSlice(location.z(), true);
if (secdMatrix.empty())
{
qWarning() << "Unable to retrieve axial slice " << location.z() << " from the water image. Matrix returned empty.";
return;
}
// The normalize function does quite a bit here. It converts the matrix to a 32-bit float and normalizes it
// between 0.0f to 1.0f based on the min/max value. This does not affect the original 3D matrix in waterImage
cv::normalize(secdMatrix.clone(), secdMatrix, 0.0f, 1.0f, cv::NORM_MINMAX, CV_32FC1);
}
break;
case SliceDisplayType::WaterFat:
{
// Get the slice for the fat image. If the result is empty then there was an error retrieving the slice