/
viewer.js
1508 lines (1393 loc) · 52.4 KB
/
viewer.js
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
import 'ol/ol.css';
import Collection from 'ol/Collection';
import Draw, { createRegularPolygon, createBox } from 'ol/interaction/Draw';
import EVENT from "./events";
import Feature from 'ol/Feature';
import Fill from 'ol/style/Fill';
import FullScreen from 'ol/control/FullScreen';
import ImageLayer from 'ol/layer/Image';
import Map from 'ol/Map';
import Modify from 'ol/interaction/Modify';
import MouseWheelZoom from 'ol/interaction/MouseWheelZoom';
import OverviewMap from 'ol/control/OverviewMap';
import Projection from 'ol/proj/Projection';
import publish from "./eventPublisher";
import ScaleLine from 'ol/control/ScaleLine';
import Select from 'ol/interaction/Select';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Static from 'ol/source/ImageStatic';
import Overlay from 'ol/Overlay';
import TileLayer from 'ol/layer/Tile';
import TileImage from 'ol/source/TileImage';
import TileGrid from 'ol/tilegrid/TileGrid';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import View from 'ol/View';
import { default as PolygonGeometry } from 'ol/geom/Polygon';
import { default as PointGeometry } from 'ol/geom/Point';
import { default as LineStringGeometry } from 'ol/geom/LineString';
import { default as CircleGeometry } from 'ol/geom/Circle';
import { default as VectorEventType } from "ol/source/VectorEventType";
import { default as MapEventType } from "ol/MapEventType";
import { defaults as defaultInteractions } from 'ol/interaction';
import { getCenter } from 'ol/extent';
import { toStringXY, rotate } from 'ol/coordinate';
import { VLWholeSlideMicroscopyImage, getFrameMapping } from './metadata.js';
import { ROI } from './roi.js';
import {
generateUID,
mapPixelCoordToSlideCoord,
mapSlideCoordToPixelCoord
} from './utils.js';
import {
Point,
Multipoint,
Polyline,
Polygon,
Ellipsoid,
Ellipse
} from './scoord3d.js';
import * as DICOMwebClient from 'dicomweb-client';
/** Extracts value of Pixel Spacing attribute from metadata.
*
* @param {object} metadata - Metadata of a DICOM VL Whole Slide Microscopy Image instance
* @returns {number[]} Spacing between pixel columns and rows in millimeter
* @private
*/
function _getPixelSpacing(metadata) {
const functionalGroup = metadata.SharedFunctionalGroupsSequence[0];
const pixelMeasures = functionalGroup.PixelMeasuresSequence[0];
return pixelMeasures.PixelSpacing;
}
/** Determines whether image needs to be rotated relative to slide
* coordinate system based on direction cosines.
* We want to rotate all images such that the X axis of the slide coordinate
* system is the vertical axis (ordinate) of the viewport and the Y axis
* of the slide coordinate system is the horizontal axis (abscissa) of the
* viewport. Note that this is opposite to the Openlayers coordinate system.
* There are only planar rotations, since the total pixel matrix is
* parallel to the slide surface. Here, we further assume that rows and
* columns of total pixel matrix are parallel to the borders of the slide,
* i.e. the x and y axis of the slide coordinate system.
*
* The row direction (left to right) of the Total Pixel Matrix
* is defined by the first three values.
* The three values specify how the direction changes from the last pixel
* to the first pixel in the row along each of the three axes of the
* slide coordinate system (x, y, z), i.e. it express in which direction one
* is moving in the slide coordinate system when the COLUMN index changes.
* The column direction (top to bottom) of the Total Pixel Matrix
* is defined by the second three values.
* The three values specify how the direction changes from the last pixel
* to the first pixel in the column along each of the three axes of the
* slide coordinate system (x, y, z), i.e. it express in which direction one
* is moving in the slide coordinate system when the ROW index changes.
*
* @param {object} metadata - Metadata of a DICOM VL Whole Slide Microscopy Image instance
* @returns {number} Rotation in radians
* @private
*/
function _getRotation(metadata) {
var degrees;
if (
(metadata.ImageOrientationSlide[0] === 0) &&
(metadata.ImageOrientationSlide[1] === -1) &&
(metadata.ImageOrientationSlide[2] === 0) &&
(metadata.ImageOrientationSlide[3] === -1) &&
(metadata.ImageOrientationSlide[4] === 0) &&
(metadata.ImageOrientationSlide[5] === 0)
) {
/*
* The Total Pixel Matrix is rotated with respect to the slide coordinate
* system by 180 degrees, such that an increase along the row direction
* (left to right) leads to lower Y coordinate values and an increase
* along the column direction (top to bottom) leads to lower X coordinate
* values.
*/
degrees = 180;
} else if (
(metadata.ImageOrientationSlide[0] === 1) &&
(metadata.ImageOrientationSlide[1] === 0) &&
(metadata.ImageOrientationSlide[2] === 0) &&
(metadata.ImageOrientationSlide[3] === 0) &&
(metadata.ImageOrientationSlide[4] === -1) &&
(metadata.ImageOrientationSlide[5] === 0)
) {
/*
* The Total Pixel Matrix is rotated with respect to the slide coordinate
* system by 90 degrees, such that an increase along the row direction
* (left to right) leads to higher X coordinate values and an increase
* along the column direction (top to bottom) leads to lower Y coordinate
* values.
*/
degrees = 90;
} else if (
(metadata.ImageOrientationSlide[0] === -1) &&
(metadata.ImageOrientationSlide[1] === 0) &&
(metadata.ImageOrientationSlide[2] === 0) &&
(metadata.ImageOrientationSlide[3] === 0) &&
(metadata.ImageOrientationSlide[4] === 1) &&
(metadata.ImageOrientationSlide[5] === 0)
) {
/*
* The Total Pixel Matrix is rotated with respect to the slide coordinate
* system by 270 degrees, such that an increase along the row direction
* (left to right) leads to lower X coordinate values and an increase
* along the column direction (top to bottom) leads to higher Y coordinate
* values.
*/
degrees = 270;
} else if (
(metadata.ImageOrientationSlide[0] === 0) &&
(metadata.ImageOrientationSlide[1] === 1) &&
(metadata.ImageOrientationSlide[2] === 0) &&
(metadata.ImageOrientationSlide[3] === 1) &&
(metadata.ImageOrientationSlide[4] === 0) &&
(metadata.ImageOrientationSlide[5] === 0)
) {
/*
* The Total Pixel Matrix is aligned with the slide coordinate system
* such that an increase along the row direction (left to right) leads to
* higher Y coordinate values and an increase along the column direction
* (top to bottom) leads to higher X coordinate values.
*/
degrees = 0;
} else {
throw new Error(`Unexpected image orientation ${metadata.ImageOrientationSlide}`);
}
return degrees * (Math.PI / 180);
}
/** Converts a vector graphic from an Openlayers Geometry into a DICOM SCOORD3D
* representation.
*
* @param {object} geometry - Openlayers Geometry
* @param {Object[]} pyramid - Metadata for resolution levels of image pyramid
* @returns {Scoord3D} DICOM Microscopy Viewer Scoord3D
* @private
*/
function _geometry2Scoord3d(geometry, pyramid) {
console.info('map coordinates from pixel matrix to slide coordinate system')
const frameOfReferenceUID = pyramid[pyramid.length - 1].FrameOfReferenceUID;
const type = geometry.getType();
if (type === 'Point') {
let coordinates = geometry.getCoordinates();
coordinates = _geometryCoordinates2scoord3dCoordinates(coordinates, pyramid);
return new Point({
coordinates,
frameOfReferenceUID: frameOfReferenceUID
});
} else if (type === 'Polygon') {
/*
* The first linear ring of the array defines the outer-boundary (surface).
* Each subsequent linear ring defines a hole in the surface.
*/
let coordinates = geometry.getCoordinates()[0].map(c => {
return _geometryCoordinates2scoord3dCoordinates(c, pyramid);
});
return new Polygon({
coordinates,
frameOfReferenceUID: frameOfReferenceUID
});
} else if (type === 'LineString') {
let coordinates = geometry.getCoordinates().map(c => {
return _geometryCoordinates2scoord3dCoordinates(c, pyramid);
});
return new Polyline({
coordinates,
frameOfReferenceUID: frameOfReferenceUID
});
} else if (type === 'Circle') {
const center = geometry.getCenter();
const radius = geometry.getRadius();
// Endpoints of major and minor axis of the ellipse.
let coordinates = [
[center[0] - radius, center[1], 0],
[center[0] + radius, center[1], 0],
[center[0], center[1] - radius, 0],
[center[0], center[1] + radius, 0],
];
coordinates = coordinates.map(c => {
return _geometryCoordinates2scoord3dCoordinates(c, pyramid);
})
return new Ellipse({
coordinates,
frameOfReferenceUID: frameOfReferenceUID
});
} else {
// TODO: Combine multiple points into MULTIPOINT.
console.error(`unknown geometry type "${type}"`)
}
}
/** Converts a vector graphic from a DICOM SCOORD3D into an Openlayers Geometry
* representation.
*
* @param {Scoord3D} scoord3d - DICOM Microscopy Viewer Scoord3D
* @param {Object[]} pyramid - Metadata for resolution levels of image pyramid
* @returns {object} Openlayers Geometry
* @private
*/
function _scoord3d2Geometry(scoord3d, pyramid) {
console.info('map coordinates from slide coordinate system to pixel matrix')
const type = scoord3d.graphicType;
const data = scoord3d.graphicData;
if (type === 'POINT') {
let coordinates = _scoord3dCoordinates2geometryCoordinates(data, pyramid);
return new PointGeometry(coordinates);
} else if (type === 'POLYLINE') {
const coordinates = data.map(d => {
return _scoord3dCoordinates2geometryCoordinates(d, pyramid);
});
return new LineStringGeometry(coordinates);
} else if (type === 'POLYGON') {
const coordinates = data.map(d => {
return _scoord3dCoordinates2geometryCoordinates(d, pyramid);
});
return new PolygonGeometry([coordinates]);
} else if (type === 'ELLIPSE') {
// TODO: ensure that the ellipse represents a circle, i.e. that
// major and minor axis form a right angle and have the same length
const majorAxisCoordinates = data.slice(0, 2);
const minorAxisCoordinates = data.slice(2, 4);
// Circle is defined by two points: the center point and a point on the
// circumference.
const point1 = majorAxisCoordinates[0];
const point2 = majorAxisCoordinates[1];
let coordinates = [
[
(point1[0] + point2[0]) / parseFloat(2),
(point1[1] + point2[1]) / parseFloat(2),
0
],
point2
];
coordinates = coordinates.map(d => {
return _scoord3dCoordinates2geometryCoordinates(d, pyramid);
});
// to flat coordinates
coordinates = [...coordinates[0].slice(0, 2), ...coordinates[1].slice(0, 2)];
// flat coordinates in combination with opt_layout and no opt_radius are also accepted
// and internaly it calculates the Radius
return new CircleGeometry(coordinates, null, "XY");
} else {
console.error(`unsupported graphic type "${type}"`)
}
}
function _geometryCoordinates2scoord3dCoordinates(coordinates, pyramid) {
return _coordinateFormatGeometry2Scoord3d([coordinates[0], coordinates[1], coordinates[2]], pyramid);
}
function _scoord3dCoordinates2geometryCoordinates(coordinates, pyramid) {
return _coordinateFormatScoord3d2Geometry([coordinates[0], coordinates[1], coordinates[2]], pyramid)
}
/** Translates coordinates of Total Pixel Matrix in pixel unit into coordinates
* in Frame of Reference (slide coordinate system) in millimeter unit.
*
* @param {number[]|number[][]} coordinates - Coordinates in Total Pixel Matrix
* @param {Object[]} pyramid - Metadata for resolution levels of image pyramid
* @returns {number[]|number[][]} Coordinates in Frame of Reference
* @private
*/
function _coordinateFormatGeometry2Scoord3d(coordinates, pyramid) {
let transform = false;
if (!Array.isArray(coordinates[0])) {
coordinates = [coordinates];
transform = true;
}
const metadata = pyramid[pyramid.length - 1];
const origin = metadata.TotalPixelMatrixOriginSequence[0];
const orientation = metadata.ImageOrientationSlide;
const spacing = _getPixelSpacing(metadata);
const offset = [
Number(origin.XOffsetInSlideCoordinateSystem),
Number(origin.YOffsetInSlideCoordinateSystem),
];
coordinates = coordinates.map(c => {
const pixelCoord = [c[0], -(c[1] + 1)];
const slideCoord = mapPixelCoordToSlideCoord({
orientation,
spacing,
offset,
point: pixelCoord
});
return [slideCoord[0], slideCoord[1], 0];
});
if (transform) {
return coordinates[0];
}
return coordinates;
}
/** Translates coordinates of coordinates in Frame of Reference
* (slide coordinate system) in millimeter unit into coordinates in
* Total Pixel Matrix in pixel unit.
*
* @param {number[]|number[][]} coordinates - Coordinates in Frame of Reference
* @param {Object[]} pyramid - Metadata for resolution levels of image pyramid
* @returns {number[]|number[][]} Coordinates in Total Pixel Matrix
* @private
*/
function _coordinateFormatScoord3d2Geometry(coordinates, pyramid) {
let transform = false;
if (!Array.isArray(coordinates[0])) {
coordinates = [coordinates];
transform = true;
}
const metadata = pyramid[pyramid.length - 1];
const orientation = metadata.ImageOrientationSlide;
const spacing = _getPixelSpacing(metadata);
const origin = metadata.TotalPixelMatrixOriginSequence[0];
const offset = [
Number(origin.XOffsetInSlideCoordinateSystem),
Number(origin.YOffsetInSlideCoordinateSystem),
];
let outOfFrame = false
coordinates = coordinates.map(c => {
if (c[0] > 25 || c[1] > 76) {
outOfFrame = true
}
const slideCoord = [c[0], c[1]];
const pixelCoord = mapSlideCoordToPixelCoord({
offset,
orientation,
spacing,
point: slideCoord
});
return [pixelCoord[0], -(pixelCoord[1] + 1), 0];
});
if (transform) {
return coordinates[0];
}
if (outOfFrame) {
console.warning(
'found coordinates outside slide coordinate system 25 x 76 mm'
)
}
return coordinates;
}
/** Extracts and transforms the region of interest (ROI) from an Openlayers
* Feature.
*
* @param {object} feature - Openlayers Feature
* @param {Object[]} pyramid - Metadata for resolution levels of image pyramid
* @returns {ROI} Region of interest
* @private
*/
function _getROIFromFeature(feature, pyramid) {
if (feature !== undefined && feature !== null) {
const geometry = feature.getGeometry();
const scoord3d = _geometry2Scoord3d(geometry, pyramid);
const properties = feature.getProperties();
// Remove geometry from properties mapping
const geometryName = feature.getGeometryName();
delete properties[geometryName];
const uid = feature.getId();
return new ROI({ scoord3d, properties, uid });
}
return
}
/** Updates the style of a feature.
*
* @param {object} styleOptions - Style options
* @param {object} styleOptions.stroke - Style options for the outline of the geometry
* @param {number[]} styleOptions.stroke.color - RGBA color of the outline
* @param {number} styleOptions.stroke.width - Width of the outline
* @param {object} styleOptions.fill - Style options for body the geometry
* @param {number[]} styleOptions.fill.color - RGBA color of the body
*/
function _setFeatureStyle(feature, styleOptions) {
if (styleOptions !== undefined) {
const style = new Style();
if ('stroke' in styleOptions) {
const strokeOptions = {
color: styleOptions.stroke.color,
width: styleOptions.stroke.width,
}
const stroke = new Stroke(strokeOptions);
style.setStroke(stroke);
}
if ('fill' in styleOptions) {
const fillOptions = {
color: styleOptions.fill.color
}
const fill = new Fill(fillOptions);
style.setFill(fill);
}
feature.setStyle(style);
}
}
const _client = Symbol('client');
const _controls = Symbol('controls');
const _drawingLayer = Symbol('drawingLayer');
const _drawingSource = Symbol('drawingSource');
const _features = Symbol('features');
const _imageLayer = Symbol('imageLayer');
const _interactions = Symbol('interactions');
const _map = Symbol('map');
const _metadata = Symbol('metadata');
const _pyramidMetadata = Symbol('pyramidMetadata');
const _pyramidFrameMappings = Symbol('pyramidFrameMappings');
const _pyramidBaseMetadata = Symbol('pyramidMetadataBase');
const _segmentations = Symbol('segmentations');
const _usewebgl = Symbol('usewebgl');
/** Interactive viewer for DICOM VL Whole Slide Microscopy Image instances
* with Image Type VOLUME.
*
* @class
* @memberof viewer
*/
class VolumeImageViewer {
/**
* Create a viewer instance for displaying VOLUME images.
*
* @param {object} options
* @param {object} options.client - A DICOMwebClient instance for interacting with an origin server over HTTP.
* @param {Object[]} options.metadata - An array of DICOM JSON metadata objects, one for each VL Whole Slide Microscopy Image instance.
* @param {string[]} [options.controls=[]] - Names of viewer control elements that should be included in the viewport.
* @param {boolean} [options.retrieveRendered=true] - Whether image frames should be retrieved via DICOMweb prerendered by the server.
* @param {boolean} [options.includeIccProfile=false] - Whether ICC Profile should be included for correction of image colors.
* @param {boolean} [options.useWebGL=true] - Whether WebGL renderer should be used.
*/
constructor(options) {
if ('useWebGL' in options) {
this[_usewebgl] = options.useWebGL;
} else {
this[_usewebgl] = true;
}
this[_client] = options.client;
if (!('retrieveRendered' in options)) {
options.retrieveRendered = true;
}
if (!('controls' in options)) {
options.controls = [];
}
options.controls = new Set(options.controls);
// Collection of Openlayers "VectorLayer" instances indexable by
// DICOM Series Instance UID
this[_segmentations] = {};
// Collection of Openlayers "Feature" instances
this[_features] = new Collection([], { unique: true });
// Add unique identifier to each created "Feature" instance
this[_features].on('add', (e) => {
// The ID may have already been set when drawn. However, features could
// have also been added without a draw event.
if (e.element.getId() === undefined) {
e.element.setId(generateUID());
}
});
/*
* To visualize images accross multiple scales, we first need to
* determine the image pyramid structure, i.e. the size and resolution
* images at the different pyramid levels.
*/
this[_metadata] = [];
options.metadata.forEach(m => {
const image = new VLWholeSlideMicroscopyImage({ metadata: m });
if (image.ImageType[2] === 'VOLUME') {
this[_metadata].push(image);
}
});
if (this[_metadata].length === 0) {
throw new Error('No VOLUME image provided.')
}
// Sort instances and optionally concatenation parts if present.
this[_metadata].sort((a, b) => {
const sizeDiff = a.TotalPixelMatrixColumns - b.TotalPixelMatrixColumns;
if (sizeDiff === 0) {
if (a.ConcatenationFrameOffsetNumber !== undefined) {
return a.ConcatenationFrameOffsetNumber - b.ConcatenationFrameOffsetNumber;
}
return sizeDiff;
}
return sizeDiff;
});
this[_pyramidMetadata] = [];
this[_pyramidFrameMappings] = [];
let frameMappings = this[_metadata].map(m => getFrameMapping(m));
for (let i = 0; i < this[_metadata].length; i++) {
const cols = this[_metadata][i].TotalPixelMatrixColumns;
const rows = this[_metadata][i].TotalPixelMatrixRows;
const numberOfFrames = this[_metadata][i].NumberOfFrames;
/*
* Instances may be broken down into multiple concatentation parts.
* Therefore, we have to re-assemble instance metadata.
*/
let alreadyExists = false;
let index = null;
for (let j = 0; j < this[_pyramidMetadata].length; j++) {
if (
(this[_pyramidMetadata][j].TotalPixelMatrixColumns === cols) &&
(this[_pyramidMetadata][j].TotalPixelMatrixRows === rows)
) {
alreadyExists = true;
index = j;
}
}
if (alreadyExists) {
// Update with information obtained from current concatentation part.
Object.assign(this[_pyramidFrameMappings][index], frameMappings[i]);
this[_pyramidMetadata][index].NumberOfFrames += numberOfFrames;
if ("PerFrameFunctionalGroupsSequence" in this[_metadata][index]) {
this[_pyramidMetadata][index].PerFrameFunctionalGroupsSequence.push(
...this[_metadata][i].PerFrameFunctionalGroupsSequence
);
}
if (!"SOPInstanceUIDOfConcatenationSource" in this[_metadata][i]) {
throw new Error(
'Attribute "SOPInstanceUIDOfConcatenationSource" is required ' +
'for concatenation parts.'
);
}
const sopInstanceUID = this[_metadata][i].SOPInstanceUIDOfConcatenationSource;
this[_pyramidMetadata][index].SOPInstanceUID = sopInstanceUID;
delete this[_pyramidMetadata][index].SOPInstanceUIDOfConcatenationSource;
delete this[_pyramidMetadata][index].ConcatenationUID;
delete this[_pyramidMetadata][index].InConcatenationNumber;
delete this[_pyramidMetadata][index].ConcatenationFrameOffsetNumber;
} else {
this[_pyramidMetadata].push(this[_metadata][i]);
this[_pyramidFrameMappings].push(frameMappings[i]);
}
}
const nLevels = this[_pyramidMetadata].length;
if (nLevels === 0) {
console.error('empty pyramid - no levels found')
}
this[_pyramidBaseMetadata] = this[_pyramidMetadata][nLevels - 1];
/*
* Collect relevant information from DICOM metadata for each pyramid
* level to construct the Openlayers map.
*/
const tileSizes = [];
const tileGridSizes = [];
const resolutions = [];
const origins = [];
const offset = [0, -1];
const basePixelSpacing = _getPixelSpacing(this[_pyramidBaseMetadata]);
const baseTotalPixelMatrixColumns = this[_pyramidBaseMetadata].TotalPixelMatrixColumns;
const baseTotalPixelMatrixRows = this[_pyramidBaseMetadata].TotalPixelMatrixRows;
const baseColumns = this[_pyramidBaseMetadata].Columns;
const baseRows = this[_pyramidBaseMetadata].Rows;
const baseNColumns = Math.ceil(baseTotalPixelMatrixColumns / baseColumns);
const baseNRows = Math.ceil(baseTotalPixelMatrixRows / baseRows);
for (let j = (nLevels - 1); j >= 0; j--) {
const columns = this[_pyramidMetadata][j].Columns;
const rows = this[_pyramidMetadata][j].Rows;
const totalPixelMatrixColumns = this[_pyramidMetadata][j].TotalPixelMatrixColumns;
const totalPixelMatrixRows = this[_pyramidMetadata][j].TotalPixelMatrixRows;
const pixelSpacing = _getPixelSpacing(this[_pyramidMetadata][j]);
const nColumns = Math.ceil(totalPixelMatrixColumns / columns);
const nRows = Math.ceil(totalPixelMatrixRows / rows);
tileSizes.push([
columns,
rows,
]);
tileGridSizes.push([
nColumns,
nRows,
]);
/*
* Compute the resolution at each pyramid level, since the zoom
* factor may not be the same between adjacent pyramid levels.
*/
let zoomFactor = baseTotalPixelMatrixColumns / totalPixelMatrixColumns;
resolutions.push(zoomFactor);
/*
* TODO: One may have to adjust the offset slightly due to the
* difference between extent of the image at a given resolution level
* and the actual number of tiles (frames).
*/
origins.push(offset);
}
resolutions.reverse();
tileSizes.reverse();
tileGridSizes.reverse();
origins.reverse();
// Functions won't be able to access "this"
const pyramid = this[_pyramidMetadata];
const pyramidFrameMappings = this[_pyramidFrameMappings];
/*
* Define custom tile URL function to retrive frames via DICOMweb WADO-RS.
*/
const tileUrlFunction = (tileCoord, pixelRatio, projection) => {
/*
* Variables x and y correspond to the X and Y axes of the slide
* coordinate system. Since we want to view the slide horizontally
* with the label on the right side, the x axis of the slide
* coordinate system is the vertical axis of the viewport and the
* y axis of the slide coordinate system the horizontal axis of the
* viewport. Note that this is in contrast to the nomenclature used
* by Openlayers.
*/
const z = tileCoord[0];
const y = tileCoord[1] + 1;
const x = tileCoord[2] + 1;
const index = x + "-" + y;
const path = pyramidFrameMappings[z][index];
if (path === undefined) {
console.warn("tile " + index + " not found at level " + z);
return (null);
}
let url = options.client.wadoURL +
"/studies/" + pyramid[z].StudyInstanceUID +
"/series/" + pyramid[z].SeriesInstanceUID +
'/instances/' + path;
if (options.retrieveRendered) {
url = url + '/rendered';
}
return (url);
}
/*
* Define custonm tile loader function, which is required because the
* WADO-RS response message has content type "multipart/related".
*/
const tileLoadFunction = (tile, src) => {
if (src !== null) {
const studyInstanceUID = DICOMwebClient.utils.getStudyInstanceUIDFromUri(src);
const seriesInstanceUID = DICOMwebClient.utils.getSeriesInstanceUIDFromUri(src);
const sopInstanceUID = DICOMwebClient.utils.getSOPInstanceUIDFromUri(src);
const frameNumbers = DICOMwebClient.utils.getFrameNumbersFromUri(src);
const img = tile.getImage();
if (options.retrieveRendered) {
const mediaType = 'image/png';
const retrieveOptions = {
studyInstanceUID,
seriesInstanceUID,
sopInstanceUID,
frameNumbers,
mediaTypes: [{ mediaType }],
};
if (options.includeIccProfile) {
retrieveOptions['queryParams'] = {
iccprofile: 'yes'
}
}
options.client.retrieveInstanceFramesRendered(retrieveOptions).then(
(renderedFrame) => {
const blob = new Blob([renderedFrame], {type: mediaType});
img.src = window.URL.createObjectURL(blob);
}
);
} else {
// TODO: support "image/jp2" and "image/jls"
const mediaType = 'image/jpeg';
const retrieveOptions = {
studyInstanceUID,
seriesInstanceUID,
sopInstanceUID,
frameNumbers,
mediaTypes: [
{ mediaType, transferSyntaxUID: '1.2.840.10008.1.2.4.50' }
]
};
options.client.retrieveInstanceFrames(retrieveOptions).then(
(rawFrames) => {
const blob = new Blob(rawFrames, {type: mediaType});
img.src = window.URL.createObjectURL(blob);
}
);
}
} else {
console.warn('could not load tile');
}
}
/** Frames may extend beyond the size of the total pixel matrix.
* The excess pixels are empty, i.e. have only a padding value.
* We set the extent to the size of the actual image without taken
* excess pixels into account.
* Note that the vertical axis is flipped in the used tile source,
* i.e. values on the axis lie in the range [-n, -1], where n is the
* number of rows in the total pixel matrix.
*/
const extent = [
0, // min X
-(baseTotalPixelMatrixRows + 1), // min Y
baseTotalPixelMatrixColumns, // max X
-1 // max Y
];
const rotation = _getRotation(this[_pyramidBaseMetadata]);
/*
* Specify projection to prevent default automatic projection
* with the default Mercator projection.
*/
const projection = new Projection({
code: 'DICOM',
units: 'metric',
extent: extent,
getPointResolution: (pixelRes, point) => {
/** DICOM Pixel Spacing has millimeter unit while the projection has
* has meter unit.
*/
const spacing = _getPixelSpacing(pyramid[nLevels - 1])[0] / 10 ** 3;
return pixelRes * spacing;
}
});
/*
* TODO: Register custom projection:
* - http://openlayers.org/en/latest/apidoc/ol.proj.html
* - http://openlayers.org/en/latest/apidoc/module-ol_proj.html#~ProjectionLike
* Direction cosines could be handled via projection rather
* than specifying a rotation
*/
/*
* We need to specify the tile grid, since DICOM allows tiles to
* have different sizes at each resolution level and a different zoom
* factor between individual levels.
*/
const tileGrid = new TileGrid({
extent: extent,
origins: origins,
resolutions: resolutions,
sizes: tileGridSizes,
tileSizes: tileSizes
});
/*
* We use the existing TileImage source but customize it to retrieve
* frames (load tiles) via DICOMweb WADO-RS.
*/
const rasterSource = new TileImage({
crossOrigin: 'Anonymous',
tileGrid: tileGrid,
projection: projection,
wrapX: false
});
rasterSource.setTileUrlFunction(tileUrlFunction);
rasterSource.setTileLoadFunction(tileLoadFunction);
this[_imageLayer] = new TileLayer({
extent: extent,
source: rasterSource,
preload: 0,
projection: projection
});
this[_drawingSource] = new VectorSource({
tileGrid: tileGrid,
projection: projection,
features: this[_features],
wrapX: false
});
this[_drawingLayer] = new VectorLayer({
extent: extent,
source: this[_drawingSource],
projection: projection,
updateWhileAnimating: true,
updateWhileInteracting: true,
});
const view = new View({
center: getCenter(extent),
extent: extent,
projection: projection,
resolutions: resolutions,
rotation: rotation
});
this[_interactions] = {
draw: undefined,
select: undefined,
modify: undefined
};
this[_controls] = {
scale: new ScaleLine({
units: 'metric',
className: ''
})
}
if (options.controls.has('fullscreen')) {
this[_controls].fullscreen = new FullScreen();
}
if (options.controls.has('overview')) {
const overviewImageLayer = new TileLayer({
extent: extent,
source: rasterSource,
preload: 0,
projection: projection
});
const overviewView = new View({
projection: projection,
resolutions: resolutions,
rotation: rotation
});
this[_controls].overview = new OverviewMap({
view: overviewView,
layers: [overviewImageLayer],
collapsed: false,
collapsible: false,
});
}
/** Creates the map with the defined layers and view and renders it. */
this[_map] = new Map({
layers: [this[_imageLayer], this[_drawingLayer]],
view: view,
controls: [],
keyboardEventTarget: document,
});
this[_map].addInteraction(new MouseWheelZoom());
for (let control in this[_controls]) {
this[_map].addControl(this[_controls][control]);
}
this[_map].getView().fit(extent);
}
/** Resizes the viewer to fit the viewport. */
resize() {
this[_map].updateSize();
}
/** Gets the size of the viewport.
*
* @type {number[]}
*/
get size() {
return this[_map].getSize();
}
/** Renders the images in the specified viewport container.
* @param {object} options - Rendering options.
* @param {(string|HTMLElement)} options.container - HTML Element in which the viewer should be injected.
*/
render(options) {
if (!('container' in options)) {
console.error('container must be provided for rendering images')
}
this[_map].setTarget(options.container);
// Style scale element (overriding default Openlayers CSS "ol-scale-line")
let scaleElement = this[_controls]['scale'].element;
scaleElement.style.position = 'absolute';
scaleElement.style.right = '.5em';
scaleElement.style.bottom = '.5em';
scaleElement.style.left = 'auto';
scaleElement.style.padding = '2px';
scaleElement.style.backgroundColor = 'rgba(255,255,255,.5)';
scaleElement.style.borderRadius = '4px';
scaleElement.style.margin = '1px';
let scaleInnerElement = this[_controls]['scale'].innerElement_;
scaleInnerElement.style.color = 'black';
scaleInnerElement.style.fontWeight = '600';
scaleInnerElement.style.fontSize = '10px';
scaleInnerElement.style.textAlign = 'center';
scaleInnerElement.style.borderWidth = '1.5px';
scaleInnerElement.style.borderStyle = 'solid';
scaleInnerElement.style.borderTop = 'none';
scaleInnerElement.style.borderRightColor = 'black';
scaleInnerElement.style.borderLeftColor = 'black';
scaleInnerElement.style.borderBottomColor = 'black';
scaleInnerElement.style.margin = '1px';
scaleInnerElement.style.willChange = 'contents,width';
const container = this[_map].getTargetElement();
this[_drawingSource].on(VectorEventType.ADDFEATURE, (e) => {
publish(container, EVENT.ROI_ADDED, _getROIFromFeature(e.feature, this[_pyramidMetadata]));
});
this[_drawingSource].on(VectorEventType.CHANGEFEATURE, (e) => {
if (e.feature !== undefined || e.feature !== null) {
const geometry = e.feature.getGeometry();
const type = geometry.getType();
// The first and last point of a polygon must be identical. The last point
// is an implmentation detail and is hidden from the user in the graphical
// interface. However, we must update the last point in case the first
// piont has been modified by the user.
if (type === 'Polygon') {
// NOTE: Polyon in GeoJSON format contains an array of geometries,
// where the first element represents the coordinates of the outer ring
// and the second element represents the coordinates of the inner ring
// (in our case the inner ring should not be present).
const layout = geometry.getLayout();
const coordinates = geometry.getCoordinates();
const firstPoint = coordinates[0][0];
const lastPoint = coordinates[0][coordinates[0].length - 1];
if (firstPoint[0] !== lastPoint[0] || firstPoint[1] !== lastPoint[1]) {
coordinates[0][coordinates[0].length - 1] = firstPoint;
geometry.setCoordinates(coordinates, layout);
e.feature.setGeometry(geometry);
}
}
}
publish(container, EVENT.ROI_MODIFIED, _getROIFromFeature(e.feature, this[_pyramidMetadata]));
});
this[_drawingSource].on(VectorEventType.REMOVEFEATURE, (e) => {
publish(container, EVENT.ROI_REMOVED, _getROIFromFeature(e.feature, this[_pyramidMetadata]));
});
}
/** Activates the draw interaction for graphic annotation of regions of interest.
* @param {object} options - Drawing options.
* @param {string} options.geometryType - Name of the geometry type (point, circle, box, polygon, freehandPolygon, line, freehandLine)
* @param {object} options.strokeStyle - Style of the geometry stroke (keys: "color", "width")
* @param {object} options.fillStyle - Style of the geometry body (keys: "color")
*/
activateDrawInteraction(options) {
this.deactivateDrawInteraction();
console.info('activate "draw" interaction')
const customOptionsMapping = {
point: {
type: 'Point',
geometryName: 'Point'
},
circle: {
type: 'Circle',
geometryName: 'Circle'
},
box: {
type: 'Circle',
geometryName: 'Box',
geometryFunction: createRegularPolygon(4),
},
polygon: {
type: 'Polygon',
geometryName: 'Polygon',
freehand: false,
},
freehandpolygon: {
type: 'Polygon',
geometryName: 'FreeHandPolygon',
freehand: true,
},
line: {
type: 'LineString',
geometryName: 'Line',
freehand: false,
},