DWVv0.37.0

Globals


Instance Methods

mergeMeta( meta0: Record.<string, DataElement>, meta1: Record.<string, DataElement>, secondIdGetter?: function, ): Record.<string, DataElement>

Merge meta datas.

Parameters

  • meta0 (Record.<string, DataElement>) — The first data to merge.
  • meta1 (Record.<string, DataElement>) — The second data to merge.
  • secondIdGetter (function, optional) — Function (meta) => number|undefined called on each raw (not yet merged) meta to get its second id, added as a suffix to disambiguate metas that would otherwise share the same base id.

Returns

isEditable(target: EventTarget | null): boolean

Check if an event target is an editable element (input, select, text area or content editable): keys typed in it are not shortcuts.

Parameters

  • target (EventTarget | null) — The event target.

Returns

  • boolean — True if editable.

hasValue(element: DataElement): boolean

Check an input data element, returns true if:

  • the element is not undefined,
  • the elements' value is not undefined,
  • the elements' value has content.

Parameters

Returns

  • boolean — True if there is a value.

safeGet( dataElements: Record.<string, DataElement>, key: string, ): any | undefined

Safely get an elements' first value from a list of elements.

Parameters

  • dataElements (Record.<string, DataElement>) — A list of data elements.
  • key (string) — The tag key as for example '00100020'.

Returns

  • any | undefined — The elements' value or undefined.

safeGetAll( dataElements: Record.<string, DataElement>, key: string, ): Array.<any> | undefined

Safely get all of an elements' values from a list of elements.

Parameters

  • dataElements (Record.<string, DataElement>) — A list of data elements.
  • key (string) — The tag key as for example '00100020'.

Returns

  • Array.<any> | undefined — The elements' values or undefined.

checkDataElement( element: DataElement, name: string, values?: Array, ): string

Check a DICOM data element: checks

  • if the element is not undefined,
  • if the elements' value is not undefined,
  • if the elements' value is not empty,
  • (optional) if the elements' values have specific values.

Parameters

  • element (DataElement) — The element to check.
  • name (string) — The element name.
  • values (Array, optional) — Optional list of expected values.

Returns

  • string — A warning if the element is not as expected.

isNativeLittleEndian(): boolean

Is the Native endianness Little Endian.

Returns

  • boolean — True if little endian.

flipArrayEndianness(array: object)

Flip an array's endianness. Inspired from DataStream.js.

Parameters

  • array (object) — The array to flip (modified).

isEqualCode(code1: DicomCode, code2: DicomCode): boolean

Check if two code objects are equal: just checks schemeDesignator and value.

Parameters

Returns

  • boolean — True if both codes are equal.

getCode(dataElements: Record.<string, DataElement>): DicomCode

Get a code object from a dicom element.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom element.

Returns

getDicomCodeItem(code: DicomCode): SimpleTagValues

Get a simple dicom element item from a code object.

Parameters

Returns

getDcmDicomCode(code: object): DicomCode

Get a DICOM code from a value and meaning.

Parameters

  • code (object) — The code value as {value, meaning}.

Returns

getDicomCode( value: string, scheme: string, ): DicomCode | undefined

Get a DICOM code from a value (~id).

Parameters

  • value (string) — The code value.
  • scheme (string) — The scheme designator.

Returns

getSegmentationCode(): DicomCode

Get a segmentation DICOM code.

Returns

getColourCode(): DicomCode

Get a colour DICOM code.

Returns

getConceptNameCode(name: string): DicomCode | undefined

Get a concept name DICOM code.

Parameters

  • name (string) — The measurment name as defined in a quantification object.

Returns

getQuantificationName(code: DicomCode): string | undefined

Get the DICOM code for a quantification name.

Parameters

Returns

  • string | undefined — The quantification name.

getMeasurementUnitsCode(name: string): DicomCode | undefined

Get a measurement units DICOM code.

Parameters

  • name (string) — The unit name as defined in a quantification object.

Returns

getQuantificationUnit(code: DicomCode): string

Get a quantification unit name.

Parameters

  • code (DicomCode) — The code to get the unit from.

Returns

  • string — The quantification unit.

getDateObj(element: DataElement): DateObj | undefined

Get a 'date' object with {year, monthIndex, day} ready for the Date constructor from a DICOM element with vr=DA.

Parameters

  • element (DataElement) — The DICOM element with date information.

Returns

  • DateObj | undefined — The 'date' object.

getTimeObj(element: DataElement): TimeObj | undefined

Get a time object with {hours, minutes, seconds} ready for the Date constructor from a DICOM element with vr=TM.

Parameters

  • element (DataElement) — The DICOM element with date information.

Returns

  • TimeObj | undefined — The time object.

getTimeInSeconds(element: DataElement): number | undefined

Get the number of seconds since midnight from a DICOM element with vr=TM.

Parameters

  • element (DataElement) — The DICOM element with time information.

Returns

  • number | undefined — The number of seconds, or undefined if the element is absent or not a valid time.

getDate(dateObj: DateObj, timeObj?: TimeObj): Date | undefined

Get a javascript Date object from objects with date information.

Parameters

  • dateObj (DateObj) — The date object.
  • timeObj (TimeObj, optional) — Optional time object.

Returns

  • Date | undefined — The full date.

getDateTimeObj(element: DataElement): Object | undefined

Get a 'dateTime' object with {date, time} ready for the Date constructor from a DICOM element with vr=DT.

Parameters

  • element (DataElement) — The DICOM element with date-time information.

Returns

  • Object | undefined — The time object.

dateToDateObj(date: Date): DateObj | undefined

Extract date values from a Date object.

Parameters

  • date (Date) — The input date.

Returns

  • DateObj | undefined — A 'date' object.

dateToTimeObj(date: Date): TimeObj | undefined

Extract time values from a Date object.

Parameters

  • date (Date) — The input date.

Returns

  • TimeObj | undefined — A 'time' object.

getDicomDate(dateObj: DateObj): string | undefined

Get a DICOM formated date string 'YYYYMMDD'.

Parameters

  • dateObj (DateObj) — The date to format.

Returns

  • string | undefined — The formated date.

getDicomTime(dateObj: TimeObj): string | undefined

Get a DICOM formated time string as 'HHMMSS'.

Parameters

  • dateObj (TimeObj) — The date object to format.

Returns

  • string | undefined — The formated time.

getDicomDateTime(datetime: Object): string | undefined

Get a DICOM formated datetime string.

Parameters

  • datetime (Object) — The datetime to format.

Returns

  • string | undefined — The formated datetime.

getFileListFromDicomDir(data: object): Array | undefined

Get the file list from a DICOMDIR.

Parameters

  • data (object) — The buffer data of the DICOMDIR.

Returns

  • Array | undefined — The file list as an array ordered by STUDY > SERIES > IMAGES.

getDicomDirFileList( dicomElements: Record.<string, DataElement>, ): Array | undefined

Get a DICOMDIR file list.

Parameters

  • dicomElements (Record.<string, DataElement>) — The dicom elements.

Returns

  • Array | undefined — The file list as an array ordered by STUDY > SERIES > IMAGES.

dcmdump(dicomElements: Record.<string, DataElement>): string

Dump the DICOM tags to a string in the same way as the DCMTK dcmdump command (https://support.dcmtk.org/docs-dcmrt/dcmdump.html).

Parameters

  • dicomElements (Record.<string, DataElement>) — The dicom elements.

Returns

  • string — The dumped file.

isBinaryVR(vr: string): boolean

Is the input VR a binary VR: 'O'ther or Unknown (UN).

Parameters

  • vr (string) — The value representation.

Returns

  • boolean — True if binary.

getElementValueAsString( tag: Tag, dicomElement: DataElement, pretty?: boolean, ): string

Get a data element value as a string.

Parameters

  • tag (Tag) — The DICOM tag.
  • dicomElement (DataElement) — The DICOM element.
  • pretty (boolean, optional) — When set to true, returns a 'pretified' content.

Returns

  • string — A string representation of the DICOM element.

getValueLength( tag: Tag, dicomElement: DataElement, isImplicit: boolean, ): number

Get the value length (in bytes) of a data element, as it would be written. The parser does not keep the read value length, so it is computed from the parsed value. String lengths are computed using UTF-8, they can differ from the written ones for non ASCII characters with other character sets.

Parameters

  • tag (Tag) — The DICOM tag.
  • dicomElement (DataElement) — The DICOM element.
  • isImplicit (boolean) — Does the data use implicit VR?

Returns

  • number — The value length.

getItemContentLength( item: Record.<string, DataElement>, isImplicit: boolean, ): number

Get the length (in bytes) of the content of a sequence item.

Parameters

  • item (Record.<string, DataElement>) — The sequence item.
  • isImplicit (boolean) — Does the data use implicit VR?

Returns

  • number — The item content length.

getItemLength( item: Record.<string, DataElement>, isImplicit: boolean, ): number

Get the length (in bytes) of a sequence item, including its item and item delimitation elements.

Parameters

  • item (Record.<string, DataElement>) — The sequence item.
  • isImplicit (boolean) — Does the data use implicit VR?

Returns

  • number — The item length.

getLine( prefix: string, tag: Tag, vr: string, value: string, length: string, multiplicity: number, name: string, ): string

Get a dump line.

Parameters

  • prefix (string) — A string to prepend to the line.
  • tag (Tag) — The DICOM tag.
  • vr (string) — The value representation.
  • value (string) — The value string.
  • length (string) — The value length string.
  • multiplicity (number) — The value multiplicity.
  • name (string) — The tag name.

Returns

  • string — The line.

getElementAsString( tag: Tag, dicomElement: DataElement, prefix: string, isImplicit: boolean, ): string

Get a data element as a string.

Parameters

  • tag (Tag) — The DICOM tag.
  • dicomElement (DataElement) — The DICOM element.
  • prefix (string) — A string to prepend this one.
  • isImplicit (boolean) — Does the data use implicit VR?

Returns

  • string — The element as a string.

getDimensionOrganization( dataElements: Record.<string, DataElement>, ): object

Check the dimension organization from a dicom element.

Parameters

  • dataElements (Record.<string, DataElement>) — The root dicom element.

Returns

  • object — The dimension organizations and indices.

getFunctionalGroup( dataElements: Record.<string, DataElement>, ): DicomFunctionalGroup | undefined

Get a functional group object from a dicom element.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom element.

Returns

getPerFrameFunctionalGroups( dataElements: Record.<string, DataElement>, numberOfFrames?: number, ): Array.<DicomFunctionalGroup> | undefined

Get the list of per frame DicomFunctionalGroup from the root list of data elements.

Parameters

  • dataElements (Record.<string, DataElement>) — The root dicom element.
  • numberOfFrames (number, optional) — Optional number of frames to compare with per frame sequence size.

Returns

isEqualFunctionalGroup( group1: DicomFunctionalGroup, group2: DicomFunctionalGroup, ): boolean

Check if two functional group objects are equal.

Parameters

Returns

  • boolean — True if both groups are equal.

getDicomFunctionalGroupItem( funcGroup: DicomFunctionalGroup, ): SimpleTagValues

Get a dicom item from a functional group object.

Parameters

Returns

getConstantPerFrameValue( elements: Record.<string, DataElement>, valueGetter: function, name: string, ): any | undefined

Get a value that is constant across the frames of a multi-frame file. Frames without the value are ignored.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.
  • valueGetter (function) — The per frame functional group value getter.
  • name (string) — The value name, used for logging.

Returns

  • any | undefined — The value, or undefined if absent or if it varies across frames: the file then does not represent a single volume and the value cannot be used as a volume id.

getFrameElements( elements: Record.<string, DataElement>, frameNumber: number, ): Record.<string, DataElement>

Get the DICOM tags of one frame of a multi-frame file: the root tags with a per frame functional groups sequence that only contains the frame item. Getters written for the root tags (for example using getConstantPerFrameValue) then return the frame value.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.
  • frameNumber (number) — The frame number.

Returns

  • Record.<string, DataElement> — The frame DICOM tags.

getFramesElements( elements: Record.<string, DataElement>, ): Array.<Record.<string, DataElement>>

Get the DICOM tags of each frame of a multi-frame file (see getFrameElements).

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

  • Array.<Record.<string, DataElement>> — The DICOM tags of each frame, the input tags if there are no per frame functional groups.

getRootGeometry(dataElements: DataElements): Geometry

Get the image geometry from root DICOM elements.

Parameters

Returns

checkDistance( frameOrigin: Point3D, refOrigin: Point3D, index: number, )

Check the distance between a frame origin and a reference origin.

Parameters

  • frameOrigin (Point3D) — The frame origin to check.
  • refOrigin (Point3D) — The reference origin to check against.
  • index (number) — The frame index, used for error message.

Throws

  • Error — If distance is too high.

completeOriginsFromReference( frameOrigins: Array.<Point3D>, refOrigins: Array.<Point3D>, ): Array.<Point3D>

Complete origins using reference origins if with gaps.

frameOrigins are not assumed to be in reference (ascending) order: a DICOM file's PerFrameFunctionalGroupsSequence frame order is not guaranteed to be spatially sorted for any writer. Match each frame to its closest reference origin first, then rebuild the continuous run in ascending reference order, filling any true gaps from refOrigins.

Parameters

  • frameOrigins (Array.<Point3D>) — The frame origins.
  • refOrigins (Array.<Point3D>) — The reference image origins.

Returns

  • Array.<Point3D> — The continous origins, in ascending reference order.

completeOriginsFromGeometry( frameOrigins: Array.<Point3D>, baseGeometry: Geometry, ): Array.<Point3D>

Complete origins using a base geometry if with gaps.

Parameters

  • frameOrigins (Array.<Point3D>) — The frame origins.
  • baseGeometry (Geometry) — The base geometry.

Returns

  • Array.<Point3D> — The continous origins.

getFramesGeometry( dataElements: DataElements, perFrameFuncGroups: Array.<DicomFunctionalGroup>, completeOrigins?: boolean, refOrigins?: Array.<Point3D>, ): Geometry

Get the frames geometry from root DICOM elements and per-frame infos.

Parameters

  • dataElements (DataElements) — The DICOM data elements.
  • perFrameFuncGroups (Array.<DicomFunctionalGroup>) — The per-frame functional groups.
  • completeOrigins (boolean, optional) — Flag to complete origins if gaps, defaults to false.
  • refOrigins (Array.<Point3D>, optional) — Reference origins used to complete gaps, if not present the code will calculate them if completeOrigins is true.

Returns

Throws

  • Error — Error for missing or wrong data.

getSortedFramesGeometry( dataElements: DataElements, ): Array.<Geometry> | undefined

Get the geometry of each frame from the per-frame functional groups: a one slice geometry with the frame position and the frame time. The frame time is the data volume id (if any) if the frame positions are unique. If frames share positions (several volumes in one file), the frame time is the frame volume id (see dicomVolume guessVolumeIndices).

Parameters

Returns

  • Array.<Geometry> | undefined — The list of geometries indexed by frame (encoding order) number. Undefined if there are no per-frame functional groups or if their positions are not unique and cannot be grouped into volumes.

Throws

  • Error — Error for missing or wrong data.

getImage2DSize( elements: Record.<string, DataElement>, ): Array.<number> | undefined

Extract the 2D size from dicom elements.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

  • Array.<number> | undefined — The sizes as [columns, rows] or undefined if not present.

get2DSpacingValues( elements: Record.<string, DataElement>, tagKey: string, ): Array.<number> | undefined

Get the 2D spacing values.

Parameters

  • elements (Record.<string, DataElement>) — The dicom element.
  • tagKey (string) — The tag key.

Returns

  • Array.<number> | undefined — The values if present.

get2DSpacingValuesFromFuncGroup( funcGroupElements: Record.<string, DataElement>, ): Array.<number> | undefined

Get the 2D spacing values from a functional group.

Parameters

  • funcGroupElements (Record.<string, DataElement>) — The dicom elements.

Returns

  • Array.<number> | undefined — The values if present.

getProjection2DSpacingValues( elements: Record.<string, DataElement>, ): Array.<number> | undefined

Get the pixel spacing for projection data.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

  • Array.<number> | undefined — The values if present.

getSecondaryCapture2DSpacingValues( elements: Record.<string, DataElement>, ): Array.<number> | undefined

Get the pixel spacing for secondary capture data.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

  • Array.<number> | undefined — The values if present.

getMultiFrame2DSpacingValues( elements: Record.<string, DataElement>, ): Array.<number> | undefined

Get the pixel spacing for multi-frame data.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

  • Array.<number> | undefined — The values if present.

getPixelSpacing( elements: Record.<string, DataElement>, ): Array.<number> | undefined

Get the pixel spacing from the different spacing tags.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

  • Array.<number> | undefined — The spacing as [columnSapcing, rowSpacing] or undefined if not present.

getPixelAspectRatio( elements: Record.<string, DataElement>, ): Array.<number> | undefined

Get the pixel aspect ratio.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

  • Array.<number> | undefined — The values if present.

getSpacingFromMeasure( dataElements: Record.<string, DataElement>, ): Spacing | undefined

Get a spacing object from a dicom measure element.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom element.

Returns

  • Spacing | undefined — A spacing object.

getTagPixelUnit( elements: Record.<string, DataElement>, ): string | undefined

Get pixel data unit from a list of tags.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

  • string | undefined — The unit value if available.

defaultGetTagPixelUnit( elements: Record.<string, DataElement>, ): string | undefined

Default get pixel data unit.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

  • string | undefined — The unit value if available.

getOrientationMatrix( dataElements: Record.<string, DataElement>, ): Matrix33 | undefined

Get an orientation matrix from a dicom orientation element.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom element.

Returns

  • Matrix33 | undefined — The orientation matrix.

getDicomMeasureItem(spacing: Spacing): SimpleTagValues

Get a dicom item from a measure sequence.

Parameters

  • spacing (Spacing) — The spacing object.

Returns

getDicomPlaneOrientationItem( orientation: Matrix33, ): SimpleTagValues

Get a dicom element from a plane orientation sequence.

Parameters

  • orientation (Matrix33) — The image orientation.

Returns

getPhotometricInterpretation( dataElements: Record.<string, DataElement>, ): string | undefined

Get the photometric interpretation from the data elements.

Parameters

  • dataElements (Record.<string, DataElement>) — The data elements.

Returns

  • string | undefined — The photometric interpretation value.

isMonochrome(photometricInterpretation: string): boolean

Check if an input photometricInterpretation is monochrome.

Parameters

  • photometricInterpretation (string) — The photometric interpretation.

Returns

  • boolean — True if the input string starts with 'MONOCHROME'.

isSecondatyCapture(SOPClassUID: string): boolean

Check if the received string represents a secondary capture.

Parameters

  • SOPClassUID (string) — The sop class uid.

Returns

  • boolean — True if it is secondary capture.

getReferencedSeriesUID( dataElements: Record.<string, DataElement>, ): string | undefined

Get the referenced series UID from the data elements.

Parameters

  • dataElements (Record.<string, DataElement>) — The data elements.

Returns

  • string | undefined — The referenced series UID.

getReferencedSeriesUIDFromRTStruct( dataElements: Record.<string, DataElement>, ): string | undefined

Get the referenced series UID from an RT Structure Set.

Path: ReferencedFrameOfReferenceSequence (3006,0010) → RTReferencedStudySequence (3006,0012) → RTReferencedSeriesSequence (3006,0014) → SeriesInstanceUID (0020,000E).

Parameters

  • dataElements (Record.<string, DataElement>) — The data elements.

Returns

  • string | undefined — The referenced series UID.

getImageReference( dataElements: Record.<string, DataElement>, ): ImageReference

Get a reference object from a dicom element.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom element.

Returns

getDicomImageReferenceItem(ref: ImageReference): SimpleTagValues

Get a simple dicom element item from a reference object.

Parameters

Returns

getManufacturer( elements: Record.<string, DataElement>, ): string | undefined

Get the manufacturer.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

  • string | undefined — The manufacturer.

getNormalisedManufacturer( elements: Record.<string, DataElement>, ): string | undefined

Get the normalised manufacturer.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

  • string | undefined — The manufacturer as a unique all lower case string.

getMeasuredValue( dataElements: Record.<string, DataElement>, ): MeasuredValue

Get a measured value object from a dicom element.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom element.

Returns

getDicomMeasuredValueItem(value: MeasuredValue): SimpleTagValues

Get a simple dicom element item from a measured value object.

Parameters

Returns

getNumericMeasurement( dataElements: Record.<string, DataElement>, ): NumericMeasurement

Get a measurement object from a dicom element.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom element.

Returns

getDicomNumericMeasurementItem( measurement: NumericMeasurement, ): SimpleTagValues

Get a simple dicom element item from a measurement object.

Parameters

Returns

getDwvVersion(): string

Get the version of the library.

Returns

  • string — The version of the library.

getDwvVersionUI(): string

Get the version of the library as a Unique Identifier (UI), meaning just numbers and dots.

Returns

  • string — The UI version of the library.

getDwvUIDPrefix(): string

Get the dwv UID prefix. Issued by Medical Connections Ltd (www.medicalconnections.co.uk) on 25/10/2017.

Returns

  • string — The dwv UID prefix.

getImplementationVersionName(): string

Get the value of the ImplementationVersionName tag.

Returns

  • string — The name.

getImplementationClassUID(): string

Get the value of the ImplementationClassUID tag.

Returns

  • string — The uid.

getDwvVersionFromImplementationClassUID( uid: string, ): string | undefined

Get the dwv version from the value of the ImplementationClassUID tag.

Parameters

  • uid (string) — The uid.

Returns

  • string | undefined — The dwv version.

splitVersion(version: string): Array.<string>

Split a string version into parts. The input version follows a 'm.n.p[-beta.q]' version sheme (related to semantic versioning).

Parameters

  • version (string) — The version.

Returns

  • Array.<string> — The splited version.

compareVersions(a: string, b: string): number

Compare versions. The input versions follow a 'm.n.p[-beta.q]' version sheme (related to semantic versioning).

Parameters

  • a (string) — The first version.
  • b (string) — The second version.

Returns

  • number

isVersionInBounds( version: string, min: string, max: string, ): boolean

Check if a version in inside bounds (bounds inclusives). The input version follows a 'm.n.p[-beta.q]' version sheme (related to semantic versioning).

Parameters

  • version (string) — The version to check.
  • min (string) — The minimum version.
  • max (string) — The maximum version.

Returns

  • boolean — True if the version in inside the bounds.

hasDicomPrefix(buffer: ArrayBuffer): boolean

Check that an input buffer includes the DICOM prefix 'DICM' after the 128 bytes preamble.

Ref: DICOM File Meta.

Parameters

  • buffer (ArrayBuffer) — The buffer to check.

Returns

  • boolean — True if the buffer includes the prefix.

cleanString(inputStr: string): string

Clean string: remove null characters (padding) and trim. Warning: no tests are done on the input, will fail if null or undefined or not string.

Parameters

  • inputStr (string) — The string to clean.

Returns

  • string — The cleaned string.

getUtfLabel(charSetTerm: string): string

Get the utfLabel (used by the TextDecoder) from a character set term.

References:

Parameters

  • charSetTerm (string) — The DICOM character set.

Returns

  • string — The corresponding UTF label.

removeEscapeSequences(buffer: Uint8Array): Uint8Array

Remove the ISO 2022 escape sequences from a buffer: ESC (0x1B), intermediate bytes (0x20-0x2F) and a final byte. Needed for ISO 2022 IR 149 (Korean), where the escape sequence only designates KS X 1001 to G1, so the rest decodes as EUC-KR.

Ref: DICOM Code Extensions.

Parameters

  • buffer (Uint8Array) — The input buffer.

Returns

  • Uint8Array — The buffer without escape sequences.

getReverseOrientation(ori: string): string

Get patient orientation label in the reverse direction.

Parameters

  • ori (string) — Patient Orientation value.

Returns

  • string — Reverse Orientation Label.

isImplicitTransferSyntax(syntax: string): boolean

Tell if a given syntax is an implicit one (element with no VR).

Parameters

  • syntax (string) — The transfer syntax to test.

Returns

  • boolean — True if an implicit syntax.

isBigEndianTransferSyntax(syntax: string): boolean

Tell if a given syntax is a big endian syntax.

Parameters

  • syntax (string) — The transfer syntax to test.

Returns

  • boolean — True if a big endian syntax.

isJpegBaselineTransferSyntax(syntax: string): boolean

Tell if a given syntax is a JPEG baseline one.

Parameters

  • syntax (string) — The transfer syntax to test.

Returns

  • boolean — True if a jpeg baseline syntax.

isJpegLosslessTransferSyntax(syntax: string): boolean

Tell if a given syntax is a JPEG Lossless one.

Parameters

  • syntax (string) — The transfer syntax to test.

Returns

  • boolean — True if a jpeg lossless syntax.

isJpeg2000TransferSyntax(syntax: string): boolean

Tell if a given syntax is a JPEG 2000 one.

Parameters

  • syntax (string) — The transfer syntax to test.

Returns

  • boolean — True if a jpeg 2000 syntax.

isRleTransferSyntax(syntax: string): boolean

Tell if a given syntax is a RLE (Run-length encoding) one.

Parameters

  • syntax (string) — The transfer syntax to test.

Returns

  • boolean — True if a RLE syntax.

getSyntaxDecompressionName(syntax: string): string | undefined

Tell if a given syntax needs decompression.

Parameters

  • syntax (string) — The transfer syntax to test.

Returns

  • string | undefined — The name of the decompression algorithm.

isReadSupportedTransferSyntax(syntax: string): boolean

Tell if a given syntax is supported for reading.

Parameters

  • syntax (string) — The transfer syntax to test.

Returns

  • boolean — True if a supported syntax.

getTransferSyntaxName(syntax: string): string

Get a transfer syntax name from its UID.

Parameters

  • syntax (string) — The transfer syntax UID value.

Returns

  • string — The transfer syntax name.

guessTransferSyntax(firstDataElement: DataElement): DataElement

Guess the transfer syntax from the first data element.

See https://github.com/ivmartel/dwv/issues/188 (Allow to load DICOM with no DICM preamble) for more details.

Parameters

  • firstDataElement (DataElement) — The first data element of the DICOM header.

Returns

getTypedArray( bitsAllocated: number, pixelRepresentation: number, size: number, ): IntTypedArray

Get the appropriate TypedArray in function of arguments.

Parameters

  • bitsAllocated (number) — The number of bites used to store the data: [8, 16, 32].
  • pixelRepresentation (number) — The pixel representation, 0:unsigned;1:signed.
  • size (number) — The size of the new array.

Returns

getTypedArrayLike(array: TypedArray, size: number): TypedArray

Get a new TypedArray of the same type as the input one (preserves float arrays, unlike getTypedArray).

Parameters

  • array (TypedArray) — The model array.
  • size (number) — The size of the new array.

Returns

  • TypedArray — The new array or null if the allocation failed.

logAllocationError(error: Error, size: number)

Log a typed array allocation error.

Parameters

  • error (Error) — The allocation error.
  • size (number) — The size of the array.

getDataElementPrefixByteSize( vr: string, isImplicit: boolean, ): number

Get the number of bytes occupied by a data element prefix, (without its value).

WARNING: this is valid for tags with a VR, if not sure use the 'isTagWithVR' function first.

Reference:

CODE
| Tag | VR  | VL | Value |
| 4   | 2   | 2  | X     | -> regular explicit: 8 + X
| 4   | 2+2 | 4  | X     | -> 32bit VL: 12 + X

| Tag | VL | Value |
| 4   | 4  | X     | -> implicit (32bit VL): 8 + X

| Tag | Len | Value |
| 4   | 4   | X     | -> item: 8 + X

Parameters

  • vr (string) — The Value Representation of the element.
  • isImplicit (boolean) — Does the data use implicit VR?

Returns

  • number — The size of the element prefix.

isKnownVR(vr: string): boolean

Is the input VR a known VR.

Parameters

  • vr (string) — The vr to test.

Returns

  • boolean — True if known.

getDecayedDose(elements: Record.<string, DataElement>): object

Get the decayed dose (Bq).

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements to check.

Returns

  • object — The value and a warning if the elements are not as expected.

getSuvFactor(elements: Record.<string, DataElement>): object

Get the PET SUV factor.

Ref:

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

  • object — The value and a warning if the elements are not as expected.

getRTStructFromElements( dataElements: Record.<string, DataElement>, ): Array.<RTROI>

Get a list of RTROI objects from RTSTRUCT DICOM elements.

Parameters

  • dataElements (Record.<string, DataElement>) — The DICOM data elements.

Returns

  • Array.<RTROI> — The list of RT ROIs.

getContentTemplate( dataElements: Record.<string, DataElement>, ): string | undefined

Get the content template value.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom elements.

Returns

  • string | undefined — The template as 'MappingResource'-'TemplateIdentifier'.

isEqualContentItem( item1: DicomSRContent, item2: DicomSRContent, ): boolean

Check if two content item objects are equal.

Parameters

Returns

  • boolean — True if both content items are equal.

getSRContent( dataElements: Record.<string, DataElement>, ): DicomSRContent

Get a content item object from a dicom element.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom element.

Returns

getDicomSRContentItem(content: DicomSRContent): SimpleTagValues

Get a simple dicom element item from a content item object.

Parameters

Returns

getSRContentFromValue( name: string, value: object, unit: string, relation?: string, ): DicomSRContent | undefined

Get a DicomSRContent from a value.

Parameters

  • name (string) — The value name.
  • value (object) — The value.
  • unit (string) — The values' unit.
  • relation (string, optional) — Optional content relationhip.

Returns

getSegment( dataElements: Record.<string, DataElement>, ): MaskSegment

Get a segment object from a dicom element.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom element.

Returns

isEqualSegment(seg1: MaskSegment, seg2: MaskSegment): boolean

Check if two segment objects are equal.

Parameters

Returns

  • boolean — True if both segment are equal.

isSimilarSegment(seg1: MaskSegment, seg2: MaskSegment): boolean

Check if two segment objects are similar: either the number or the displayValue are equal.

Parameters

Returns

  • boolean — True if both segment are similar.

getDicomSegmentItem(segment: MaskSegment): SimpleTagValues

Get a dicom simple tag from a segment object.

Parameters

Returns

getSopInstanceReference( dataElements: Record.<string, DataElement>, ): SopInstanceReference

Get a SOP reference object from a dicom element.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom element.

Returns

getDicomSopInstanceReferenceItem( ref: SopInstanceReference, ): SimpleTagValues

Get a simple dicom element item from a SOP reference object.

Parameters

Returns

getSpatialCoordinate( dataElements: Record.<string, DataElement>, ): SpatialCoordinate

Get a scoord object from a dicom element.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom element.

Returns

getDicomSpatialCoordinateItem( scoord: SpatialCoordinate, ): SimpleTagValues

Get a simple dicom element item from a scoord object.

Parameters

Returns

getScoordFromShape( shape: Point2D | Line | Protractor | ROI | Circle | Ellipse | Rectangle | BidimensionalLine, ): SpatialCoordinate

Get a DICOM spatial coordinate (SCOORD) from a mathematical shape. Supports all standard shapes, including BidimensionalLine (exported as a polyline with 4 points).

Parameters

Returns

getShapeFromScoord( scoord: SpatialCoordinate, ): Point2D | Line | Protractor | ROI | Circle | Ellipse | Rectangle | BidimensionalLine | undefined

Get a mathematical shape from a DICOM spatial coordinate (SCOORD). Supports all standard shapes, including BidimensionalLine (polyline with 4 points).

Parameters

Returns

getSpatialCoordinate3D( dataElements: Record.<string, DataElement>, ): SpatialCoordinate3D

Get a scoord3d object from a dicom element.

Parameters

  • dataElements (Record.<string, DataElement>) — The dicom element.

Returns

getDicomSpatialCoordinate3DItem( scoord: SpatialCoordinate3D, ): SimpleTagValues

Get a simple dicom element item from a scoord3d object.

Parameters

Returns

tagCompareFunction(a: Tag, b: Tag): number

Tag compare function.

Parameters

  • a (Tag) — The first tag.
  • b (Tag) — The second tag.

Returns

  • number — The result of the tag comparison, positive for b before a, negative for a before b and zero to keep same order.

getTagFromKey(key: string): Tag

Split a group-element key used to store DICOM elements.

Parameters

  • key (string) — The key in form "00280102" as generated by tag::getKey.

Returns

  • Tag — The DICOM tag.

getTransferSyntaxUIDTag(): Tag

Get the TransferSyntaxUID Tag.

Returns

  • Tag — The tag.

getFileMetaInformationGroupLengthTag(): Tag

Get the FileMetaInformationGroupLength Tag.

Returns

  • Tag — The tag.

isFileMetaInformationGroupLengthTag(tag: Tag): boolean

Is the input tag the FileMetaInformationGroupLength Tag.

Parameters

  • tag (Tag) — The tag to test.

Returns

  • boolean — True if the asked tag.

getItemTag(): Tag

Get the Item Tag.

Returns

  • Tag — The tag.

isItemTag(tag: Tag): boolean

Is the input tag the Item Tag.

Parameters

  • tag (Tag) — The tag to test.

Returns

  • boolean — True if the asked tag.

getItemDelimitationItemTag(): Tag

Get the ItemDelimitationItem Tag.

Returns

  • Tag — The tag.

isItemDelimitationItemTag(tag: Tag): boolean

Is the input tag the ItemDelimitationItem Tag.

Parameters

  • tag (Tag) — The tag to test.

Returns

  • boolean — True if the asked tag.

getSequenceDelimitationItemTag(): Tag

Get the SequenceDelimitationItem Tag.

Returns

  • Tag — The tag.

isSequenceDelimitationItemTag(tag: Tag): boolean

Is the input tag the SequenceDelimitationItem Tag.

Parameters

  • tag (Tag) — The tag to test.

Returns

  • boolean — True if the asked tag.

getPixelDataTag(): Tag

Get the PixelData Tag.

Returns

  • Tag — The tag.

getAllPixelDataTagKeys(): Array.<string>

Get the list of pixel data DICOM tag keys: PixelData, FloatPixelData and DoubleFloatPixelData.

Returns

  • Array.<string> — The key list.

isAnyPixelDataTag(tag: Tag): boolean

Is the input tag one of the pixel data tag.

Parameters

  • tag (Tag) — The tag to test.

Returns

  • boolean — True if input is a pixel data tag.

getAnyPixelDataElement( elements: Record.<string, DataElement>, ): DataElement | undefined

Get the dicom data element for the pixel data (can be regular, float or double data).

Parameters

  • elements (Record.<string, DataElement>) — The data elements.

Returns

hasAnyPixelDataElement( elements: Record.<string, DataElement>, ): boolean

Check if an input data elements contains a pixel data element.

Parameters

  • elements (Record.<string, DataElement>) — Data elements.

Returns

  • boolean — True if the elements contain one of the pixel data tags.

getDicomTagInfo(tag: Tag): TagInfo | undefined

Get the DICOM tag info for a tag using the local DICOM tag dictionary.

Parameters

  • tag (Tag) — The DICOM tag.

Returns

  • TagInfo | undefined — The info.

getDicomTagGroupName(tag: Tag): string | undefined

Get the DICOM tag group name as defined in TagGroups.

Parameters

  • tag (Tag) — The DICOM tag.

Returns

  • string | undefined — The group name.

getTagFromDictionary(tagName: string): Tag | undefined

Get a tag from the dictionary using a tag string name.

Parameters

  • tagName (string) — The tag string name.

Returns

  • Tag | undefined — The tag object or undefined if bad input or not found.

createSourcedValue( value: number | undefined, tagKey: string, unit?: string, ): SourcedNumberValue | undefined

Create a sourced number value.

Parameters

  • value (number | undefined) — The value.
  • tagKey (string) — The key of the tag the value is read from.
  • unit (string, optional) — The value unit as an i18n key.

Returns

  • SourcedNumberValue | undefined — The sourced value, undefined if the value is undefined.

getDiffusionBValueFromFunctionalSeq( elements: Record.<string, DataElement>, ): string | undefined

Get the diffusion b-value from a functional DICOM sequence.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

  • string | undefined — The value, if present.

getStandardDiffusionBValueFromEMR( elements: Record.<string, DataElement>, ): string | undefined

Get the diffusion b-value from standard DICOM tag.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

  • string | undefined — The value, if present.

getPrivateTagValue( elements: Record.<string, DataElement>, key: string, ): string | undefined

Get the first value of a private tag. Private tags read from implicit VR data are not in the dictionary and are parsed as 'UN', their value is then the raw bytes: decode them as an ASCII string.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.
  • key (string) — The tag key.

Returns

  • string | undefined — The value, if present.

getNonStandardDiffusionBValueFromMR( elements: Record.<string, DataElement>, ): Object | undefined

Get the diffusion b-value from MR from non standard and/or private DICOM tags.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

  • Object | undefined — The value and the key of the tag it was read from, if present.

hasBValueDimensionPointer( elements: Record.<string, DataElement>, ): boolean

Check if the dimension index sequence has a pointer to the b-value.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

  • boolean — True if a b-value pointer is present.

getPhilipsFrameBValueIndex( group: Record.<string, DataElement>, ): number | undefined

Get the b-value dimension index value of a frame. Hard coded logic based on real cases...

Parameters

  • group (Record.<string, DataElement>) — The per frame functional group.

Returns

  • number | undefined — The value, if present.

getPhilipsDiffusionBValueFromEMR( elements: Record.<string, DataElement>, ): number | undefined

Get the b-value from the frame content sequence if the dimension index sequence has a pointer to the b-value. Note: the value is a dimension index, not the b-value itself.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

  • number | undefined — The value, if present.

getNonStandardDiffusionBValueFromEMR( elements: Record.<string, DataElement>, ): number | undefined

Get the diffusion b-value from Enhanced MR from non standard and/or private DICOM tags.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

  • number | undefined — The value, if present.

parseNumber(value: any, parse: function): number | undefined

Parse a tag value to a number.

Parameters

  • value (any) — The value to parse.
  • parse (function) — The string to number parser to use.

Returns

  • number | undefined — The number, or undefined if the value is absent or not a number.

getDiffusionBValueVolumeId( elements: Record.<string, DataElement>, ): SourcedNumberValue | undefined

Get the diffusion b-value as a volume id: with the key of the tag it was read from and its unit (no unit if the value is not a b-value, for example a dimension index).

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

getMRVolumeId( elements: Record.<string, DataElement>, ): SourcedNumberValue | undefined

Get the volume id for MR images (can be time, b-value...).

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

getFrameTemporalPositionIndex( group: Record.<string, DataElement>, ): number | undefined

Get the temporal position index of a frame.

Parameters

  • group (Record.<string, DataElement>) — The per frame functional group.

Returns

  • number | undefined — The value, if present.

getTemporalPositionIndex( elements: Record.<string, DataElement>, ): SourcedNumberValue | undefined

Get the temporal position index for enhanced multi-frame images.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

getFrameTemporalPositionTimeOffset( group: Record.<string, DataElement>, ): number | undefined

Get the temporal position time offset of a frame.

Parameters

  • group (Record.<string, DataElement>) — The per frame functional group.

Returns

  • number | undefined — The value, if present.

getTemporalPositionTimeOffset( elements: Record.<string, DataElement>, ): SourcedNumberValue | undefined

Get the temporal position time offset (in seconds) for enhanced multi-frame images.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

makeNumericTagGetter( key: string, parse: function, unit?: string, ): function

Create a getter that reads a numeric value from a single tag.

Parameters

  • key (string) — The tag key.
  • parse (function) — The string to number parser to use.
  • unit (string, optional) — The value unit as an i18n key.

Returns

  • function — The getter, returns undefined if the tag is absent or not a number.

warnDeprecatedOnce(message: string)

Log a deprecation warning, only once per message.

Parameters

  • message (string) — The deprecation message.

getCandidateVolumeId( candidate: VolumeIdCandidate, elements: Record.<string, DataElement>, ): VolumeId | undefined

Get the volume id of a candidate, its id named after the candidate.

Parameters

Returns

  • VolumeId | undefined — The volume id, if present with a number id.

getDeprecatedCandidate(getter: function): VolumeIdCandidate

Get a deprecated custom volume id getter as a candidate: its getter returns a number.

Parameters

  • getter (function) — The deprecated getter.

Returns

getVolumeId( elements: Record.<string, DataElement>, ): VolumeId | undefined

Get the volume id from a list of tags, used while loading (before the full data is known): the first defined volume id of the candidates flagged with preLoad (see defaultVolumeIdCandidates).

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

  • VolumeId | undefined — The volume id if available.

getVolumeIdTagValue( elements: Record.<string, DataElement>, ): number | undefined

Get the volume id number from a list of tags, used while loading (see getVolumeId).

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

  • number | undefined — The id if available.

getDateTimeInSeconds( elements: Record.<string, DataElement>, dateKey: string, timeKey: string, ): SourcedNumberValue | undefined

Get a time as a number of seconds. If the date is available, it is included so that times spanning midnight are correctly ordered.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.
  • dateKey (string) — The date tag key.
  • timeKey (string) — The time tag key.

Returns

getAcquisitionTime( elements: Record.<string, DataElement>, ): SourcedNumberValue | undefined

Get the acquisition time as a number of seconds (see getDateTimeInSeconds).

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

getContentTime( elements: Record.<string, DataElement>, ): SourcedNumberValue | undefined

Get the content time as a number of seconds (see getDateTimeInSeconds).

Parameters

  • elements (Record.<string, DataElement>) — The DICOM tags.

Returns

getVolumeIdCandidates(): Array.<VolumeIdCandidate>

Get the list of volume id candidates: the custom one if defined, the default one otherwise.

Returns

getVolumeIdCandidate( name: string, ): VolumeIdCandidate | undefined

Get a volume id candidate from its name, including the deprecated custom getters (named 'custom').

Parameters

  • name (string) — The candidate name.

Returns

getVolumeIndices( values: Array.<any>, sliceIndices: Array.<number>, numberOfSlices: number, ): Array.<number> | undefined

Get the volume index of each item (file or frame) from its volume id. The grouping is valid if all items have a numeric id, there are at least two distinct ids and each (slice, volume) pair is unique with a total of slices times volumes items: every volume then contains every slice.

Parameters

  • values (Array.<any>) — The volume id of each item.
  • sliceIndices (Array.<number>) — The slice index of each item.
  • numberOfSlices (number) — The number of distinct slices.

Returns

  • Array.<number> | undefined — The volume index of each item (volumes ordered by ascending id), undefined if the grouping is not valid.

getCandidateVolumeValues( candidate: VolumeIdCandidate, elementsList: Array.<Record.<string, DataElement>>, volumeIndices: Array.<number>, ): Array.<SourcedNumberValue> | undefined

Get the associated value of each volume from a value candidate: the smallest value of the volume (relative to the one of the first volume for relative candidates). Each volume spans from its smallest to its largest value, the spans must not overlap and must follow the volume order.

Parameters

  • candidate (VolumeIdCandidate) — The candidate.
  • elementsList (Array.<Record.<string, DataElement>>) — The DICOM tags of each item.
  • volumeIndices (Array.<number>) — The volume index of each item.

Returns

  • Array.<SourcedNumberValue> | undefined — The associated value of each volume, undefined if the candidate is not valid.

guessVolumeValues( elementsList: Array.<Record.<string, DataElement>>, volumeIndices: Array.<number>, ): Array.<SourcedNumberValue> | undefined

Guess the associated value of each volume: value candidates are tried in order, the first valid one is kept (see volumeValueCandidates).

Parameters

  • elementsList (Array.<Record.<string, DataElement>>) — The DICOM tags of each item.
  • volumeIndices (Array.<number>) — The volume index of each item.

Returns

  • Array.<SourcedNumberValue> | undefined — The associated value of each volume, undefined if no candidate is valid.

getVolumeValues( volumeIds: Array.<VolumeId>, elementsList: Array.<Record.<string, DataElement>>, ): Array.<SourcedNumberValue> | undefined

Get the associated value of each volume, once all data is loaded: the id relative to the first one for relative candidates (for example AcquisitionTime), guessed for indices (ids without unit, for example TemporalPositionIdentifier, see volumeValueCandidates). Other ids have none.

Parameters

  • volumeIds (Array.<VolumeId>) — The volume ids, sorted by id (as returned by Geometry.getVolumeIds).
  • elementsList (Array.<Record.<string, DataElement>>) — The DICOM tags of each item (file or frame).

Returns

  • Array.<SourcedNumberValue> | undefined — The associated value of each volume, undefined if not available.

guessVolumeIndices( elementsList: Array.<Record.<string, DataElement>>, sliceIndices: Array.<number>, numberOfSlices: number, ): Object | undefined

Guess the volume index of items (files or frames) that share slice positions: volume id candidates are tried in order, the first one that produces a valid grouping is kept (see getVolumeIndices). If the deprecated custom.getPostLoadVolumeIdTagValue is defined, it is used as the only candidate.

Parameters

  • elementsList (Array.<Record.<string, DataElement>>) — The DICOM tags of each item.
  • sliceIndices (Array.<number>) — The slice index of each item.
  • numberOfSlices (number) — The number of distinct slices.

Returns

  • Object | undefined — The volume index and volume id of each item (without associated value, see getVolumeValues) and the volume id getter ((elements) => number|undefined) that produced them, undefined if no candidate produces a valid grouping.

getRuleElementValue(value: any): Array

Get the element value from a replace rule value: an array value is used as the element value list, a single value is put in an array. The value is cloned to not modify the rule value when writing.

Parameters

  • value (any) — The rule value.

Returns

  • Array — The element value.

cloneRuleValue(value: any): any

Deep clone a writer rule value: arrays, typed arrays, data elements and plain objects (for example sequence items) are cloned, other values (strings, numbers, tags...) are returned as is.

Parameters

  • value (any) — The value to clone.

Returns

  • any — The cloned value.

getDefaultAnonymisationRules(): Record.<string, WriterRule>

Get simple (non official) DICOM anonymisation rules.

Returns

translateWriterRules( rules: Record.<string, WriterRule>, ): Record.<string, WriterRule>

Translate writer rules indexed by tag or group name into rules indexed by tag or group key, as expected by the writer. A group name is translated into all the groups that have it (for example 'Curve' gives '5000', '5002'...). Warning: group names are not defined by the DICOM standard, they come from the GDCM group name list (see tagGroups), which does not cover all groups. Prefer group keys. Rules already indexed by key (or default) are kept as is and take precedence over translated ones. Unknown names are dropped.

Parameters

  • rules (Record.<string, WriterRule>) — The name based rules.

Returns

  • Record.<string, WriterRule> — The key based rules.

isWriterRuleKey(key: string): boolean

Check if a writer rule index is a tag key ('########') or a group key ('####'), possibly a range using 'x' as any hex digit (for example '60xx3000').

Parameters

  • key (string) — The rule index.

Returns

  • boolean — True if the index is a tag or group key.

normaliseWriterRuleKey(key: string): string

Normalise a writer rule key: upper case hex digits and lower case 'x'.

Parameters

  • key (string) — The rule key.

Returns

  • string — The normalised key.

isWriterRuleRange(key: string): boolean

Check if a writer rule key is a range (contains 'x').

Parameters

  • key (string) — The rule key.

Returns

  • boolean — True if the key is a range.

getWriterRangeRules( rules: Record.<string, WriterRule>, length: number, ): Array.<WriterRangeRule>

Get the range rules of a given key length, sorted by specificity: the ones with less 'x' first.

Parameters

  • rules (Record.<string, WriterRule>) — The rules.
  • length (number) — The key length: 8 for tags, 4 for groups.

Returns

findWriterRangeRule( rangeRules: Array.<WriterRangeRule>, key: string, ): WriterRule | undefined

Find the first range rule matching a key.

Parameters

  • rangeRules (Array.<WriterRangeRule>) — The sorted range rules.
  • key (string) — The tag or group key.

Returns

  • WriterRule | undefined — The matching rule if found.

getUID(tagName: string): string

Get a UID for a DICOM tag.

Note: Use https://github.com/uuidjs/uuid?

Ref:

Parameters

  • tagName (string) — The input tag.

Returns

  • string — The corresponding UID.

isEven(number: number): boolean

Return true if the input number is even.

Parameters

  • number (number) — The number to check.

Returns

  • boolean — True is the number is even.

isTypedArrayVr(vr: string): boolean

Is the input VR a VR that stores data in a typed array. TODO: include ox and xs?

Parameters

  • vr (string) — The element VR.

Returns

  • boolean — True if the VR is a typed array one.

isStringVr(vr: string): boolean

Is the input VR a string VR.

Parameters

  • vr (string) — The element VR.

Returns

  • boolean — True if the VR is a string one.

isVrToPad(vr: string): boolean

Is the input VR a VR that could need padding.

See http://dicom.nema.org/medical/dicom/2024a/output/chtml/part05/sect_6.2.html.

Parameters

  • vr (string) — The element VR.

Returns

  • boolean — True if the VR needs padding.

getVrPad(vr: string): string

Get the VR specific padding value.

Parameters

  • vr (string) — The element VR.

Returns

  • string — The value used to pad.

uint8ArrayPush( arr: Array | Uint8Array, value: Array | Uint8Array, ): Uint8Array

Push a value at the end of an input Uint8Array.

Parameters

  • arr (Array | Uint8Array) — The input array.
  • value (Array | Uint8Array) — The value to push.

Returns

  • Uint8Array — The new array.

padOBValue(value: Array | Uint8Array): Array | Uint8Array

Pad an input OB value.

Parameters

  • value (Array | Uint8Array) — The input value.

Returns

  • Array | Uint8Array — The padded input.

flattenArrayOfTypedArrays(initialArray: Array): object

Helper method to flatten an array of typed arrays to 2D typed array.

Parameters

  • initialArray (Array) — Array of typed arrays.

Returns

  • object — A typed array containing all values.

checkAndFixUnknownVR( element: DataElement, isLittleEndian?: boolean, )

Fix for broken DICOM elements: replace "UN" with correct VR if the element exists in dictionary.

Parameters

  • element (DataElement) — The DICOM element.
  • isLittleEndian (boolean, optional) — Flag to tell if the data is little or big endian (default: true).

getUint8ToVrValue( value: object, vr: string, isLittleEndian?: boolean, ): object

Get the casted typed array value from Uint8 to vr type.

Parameters

  • value (object) — The value to cast.
  • vr (string) — The DICOM element VR.
  • isLittleEndian (boolean, optional) — Flag to tell if the data is little or big endian (default: true).

Returns

  • object — The element value casted to the vr type.

getDataElement(tagName: string): DataElement

Get a DICOM element from its tag name (value set separatly).

Parameters

  • tagName (string) — The string tag name.

Returns

getBpeForVrType(vrType: string): number

Get the number of bytes per element for a given VR type.

Parameters

  • vrType (string) — The VR type as defined in the dictionary.

Returns

  • number — The bytes per element.

addTagsToDictionary( group: string, tags: Record.<string, Array.<string>>, )

Add tags to the dictionary.

Parameters

  • group (string) — The group key.
  • tags (Record.<string, Array.<string>>) — The tags to add as an object indexed by element key with values as: [VR, multiplicity, TagName] (all strings).

is32bitVLVR(vr: string): boolean

Does the input Value Representation (VR) have a 32bit Value Length (VL).

Parameters

  • vr (string) — The data Value Representation (VR).

Returns

  • boolean — True if this VR has a 32-bit VL.

isCharSetStringVR(vr: string): boolean

Does the input Value Representation (VR) have an special character repertoire.

Parameters

  • vr (string) — The data VR.

Returns

  • boolean — True if this VR has a special char set.

getDataElementsReducer( dataElements: Record.<string, DataElement>, ): function

Get an array reducer to reduce an array of tag keys taken from the input dataElements and return as simple tag values.

Parameters

  • dataElements (Record.<string, DataElement>) — The meta data index by tag keys.

Returns

  • function — An array reducer callbackFn (accumulator, currentValue).

getAsSimpleTagValues( dataElements: Record.<string, DataElement>, ): SimpleTagValues

Get the meta data as simple tag values:

  • indexed by tag names instead of tag keys,
  • no element object, just value if not sequence nor merged item.

Parameters

  • dataElements (Record.<string, DataElement>) — The data elements index by tag keys.

Returns

mergeTagValues(list1: SimpleTagValues, list2: SimpleTagValues)

Merge a simple tag value list into another. Mutates the first input.

Parameters

getElementsFromSimpleTagValues( simpleTags: SimpleTagValues, ): Record.<string, DataElement>

Get the DICOM elements from a 'simple' DICOM tags object. The input object is a simplified version of the oficial DICOM json with tag names instead of keys and direct values (no value property) for simple tags. See synthetic test data (in tests/dicom) for examples.

Parameters

Returns

isVolumeOnlyMove(diffDims?: Array.<number>): boolean

Check if only non spatial dimensions changed.

Parameters

  • diffDims (Array.<number>, optional) — The modified dimensions.

Returns

  • boolean — True if only non spatial dimensions changed.

isUnchangedPosition(diffDims?: Array.<number>): boolean

Check if the position index did not change.

Parameters

  • diffDims (Array.<number>, optional) — The modified dimensions.

Returns

  • boolean — True if no index dimension changed.

getBoundPosition( vc: ViewController, values: Array.<number>, keepVolume: boolean, diffDims?: Array.<number>, ): Point

Get the bound position of a target view.

Parameters

  • vc (ViewController) — The target view controller.
  • values (Array.<number>) — The source position values.
  • keepVolume (boolean) — True to keep the target volume.
  • diffDims (Array.<number>, optional) — The modified dimensions.

Returns

  • Point — The target position.

getInteractionEventOptions( eventName: string, ): AddEventListenerOptions

Get the listener options of an interaction event: only the NonPassiveInteractionEventNames are not passive.

Parameters

  • eventName (string) — The interaction event name.

Returns

  • AddEventListenerOptions — The listener options.

getTouchesPositions( touches: TouchList, rect: DOMRect, ): Array.<Point2D>

Get the positions (without the parent offset) of a list of touch events.

Parameters

  • touches (TouchList) — The list of touch events.
  • rect (DOMRect) — The bounding client rect.

Returns

  • Array.<Point2D> — The list of positions of the touch events.

getTouchPoints(event: TouchEvent): Array.<Point2D>

Get the offsets of an input touch event.

Parameters

  • event (TouchEvent) — The event to get the offset from.

Returns

  • Array.<Point2D> — The array of points.

getMousePoint(event: MouseEvent): Point2D

Get the offset of an input mouse event.

Parameters

  • event (MouseEvent) — The event to get the offset from.

Returns

canCreateCanvas( width: number, height: number, doc: Document, ): boolean

Test if a canvas with the input size can be created.

Ref:

Parameters

  • width (number) — The canvas width.
  • height (number) — The canvas height.
  • doc (Document) — The document used to create the test canvases.

Returns

  • boolean — True if the canvas can be created.

fitsIn(size: Scalar2D, other: Scalar2D): boolean

Check if a size is smaller or equal to another one in both dimensions.

Parameters

  • size (Scalar2D) — The size to check.
  • other (Scalar2D) — The size to compare to.

Returns

  • boolean — True if size fits in other.

getNumberToPrecision(precision: number): function

Get a number toprecision function with the provided precision.

Parameters

  • precision (number) — The precision to achieve.

Returns

  • function — The to precision function.

createDefaultReplaceFormat(length: number): string

Create a default replace format from a given length. For example: '{v0}, {v1}'.

Parameters

  • length (number) — The length of the format.

Returns

  • string — A replace format.

replaceFlags(inputStr: string, values: Array): string

Replace flags in a input string. Flags are keywords surrounded with curly braces in the form: '{v0}, {v1}'.

Parameters

  • inputStr (string) — The input string.
  • values (Array) — An array of values.

Returns

  • string — The result string.

Example

CODE
var values = ["a", "b"];
   var str = "The length is: {v0}. The size is: {v1}";
   var res = replaceFlags(str, values);
   // "The length is: a. The size is: b"

createInfoData( dicomElements: object, configs: Record.<string, Array.<InfoDataItem>>, ): Array.<InfoDataItem>

Create info data array for a DICOM image.

Parameters

  • dicomElements (object) — DICOM elements of the image.
  • configs (Record.<string, Array.<InfoDataItem>>) — The info data configs.

Returns

createInfoDataForDom( domElements: object, configs: Record.<string, Array.<InfoDataItem>>, ): Array.<InfoDataItem>

Create info data array for a DOM image.

Parameters

  • domElements (object) — Meta data.
  • configs (Record.<string, Array.<InfoDataItem>>) — The info data configs.

Returns

getLiKey(data: InfoDataItem): string

Get the key of the HTML li element of a data.

Parameters

Returns

  • string — The key.

getLayerDivId(groupDivId: string, layerIndex: number): string

Get the layer div id. For example: 'layerGroup0-layer-0'.

Parameters

  • groupDivId (string) — The layer group div id.
  • layerIndex (number) — The layer index.

Returns

  • string — A string id.

getLayerDetailsFromLayerDivId(idString: string): object

Get the layer details from a div id created by getLayerDivId.

Parameters

  • idString (string) — The layer div id.

Returns

  • object — The layer details as {groupDivId, layerIndex, layerId}.

getLayerDetailsFromEvent(event: object): object

Get the layer details from a mouse event.

Parameters

  • event (object) — The event to get the layer div id from. Expecting an event origininating from a canvas inside a layer HTML div with the 'layer' class and id generated with getLayerDivId.

Returns

  • object — The layer details as {groupDivId, layerIndex, layerId}.

getScaledOffset( offset: Scalar2D, scale: Scalar2D, newScale: Scalar2D, center: Scalar2D, ): Scalar2D

Get a scaled offset to adapt to new scale and such as the input center stays at the same position.

Parameters

  • offset (Scalar2D) — The previous offset as {x,y}.
  • scale (Scalar2D) — The previous scale as {x,y}.
  • newScale (Scalar2D) — The new scale as {x,y}.
  • center (Scalar2D) — The scale center as {x,y}.

Returns

  • Scalar2D — The scaled offset as {x,y}.

toUID(str: string): string

Convert a string into an UID.

Parameters

  • str (string) — The input string.

Returns

  • string — The input string converted to numbers using parseInt with a 36 radix (10 digits from 0 to 9 + 26 digits from a to z).

imageDataToBuffer(imageData: object): Uint8Array

Create a simple array buffer from an ImageData buffer.

Parameters

  • imageData (object) — The ImageData taken from a context.

Returns

  • Uint8Array — The image buffer.

getDefaultImage( width: number, height: number, sliceIndex: number, imageBuffer: object, numberOfFrames: number, imageUid: string, ): object

Get an image from an input context imageData.

Parameters

  • width (number) — The width of the coresponding image.
  • height (number) — The height of the coresponding image.
  • sliceIndex (number) — The slice index of the imageData.
  • imageBuffer (object) — The image buffer.
  • numberOfFrames (number) — The final number of frames.
  • imageUid (string) — The image UID.

Returns

  • object — The corresponding view.

getViewFromDOMImage( domImage: HTMLImageElement, origin: string | File, index: number, ): object

Get data from an input image using a canvas.

Parameters

  • domImage (HTMLImageElement) — The DOM Image, an HTMLImageElement with extra info.
  • origin (string | File) — The data origin.
  • index (number) — The data index.

Returns

  • object — A load data event.

getViewFromDOMVideo( video: object, onloaditem: function, onload: object, onprogress: object, onloadend: object, origin: string | File, dataIndex: number, )

Get data from an input image using a canvas.

Parameters

  • video (object) — The DOM Video, an HTMLVideoElement with extra info.
  • onloaditem (function) — On load callback.
  • onload (object) — The function to call once the data is loaded.
  • onprogress (object) — The function to call to report progress.
  • onloadend (object) — The function to call to report load end.
  • origin (string | File) — The data origin.
  • dataIndex (number) — The data index.

getComparePoint3D(orientation: Matrix33): comparePointFn

Get a point compare function using Z coordinate difference. Compares de-oriented points using the input orientation inverse.

Parameters

  • orientation (Matrix33) — The orientation matrix.

Returns

getClosestOriginResidual( point3D: Point3D, origins: Array.<Point3D>, orientation: Matrix33, ): Object

Get the closest of a list of origins to an input point, and the signed residual between the point and that origin, projected onto the slice-stacking direction (the orientation's 3rd column, ie its normal). A positive residual means the point is 'ahead of' (in the codirectional sense) the closest origin along that direction, a negative (or zero) residual means it is 'at or behind' it.

Parameters

  • point3D (Point3D) — The point to locate.
  • origins (Array.<Point3D>) — The origins to search.
  • orientation (Matrix33) — The geometry orientation.

Returns

  • Object — The closest origin's index in the input list and the normal-projected residual to it.

getClosestValueIndex( values: Array.<number>, value: number, ): number

Get the index of the closest value of a sorted list.

Parameters

  • values (Array.<number>) — The sorted values.
  • value (number) — The value to locate.

Returns

  • number — The index of the closest value.

getOrientedArray3D( array3D: Array.<number>, orientation: Matrix33, ): Array.<number>

Get the oriented values of an input 3D array.

Parameters

  • array3D (Array.<number>) — The 3D array.
  • orientation (Matrix33) — The orientation 3D matrix.

Returns

  • Array.<number> — The values reordered according to the orientation.

getDeOrientedArray3D( array3D: Array.<number>, orientation: Matrix33, ): Array.<number>

Get the raw values of an oriented input 3D array.

Parameters

  • array3D (Array.<number>) — The 3D array.
  • orientation (Matrix33) — The orientation 3D matrix.

Returns

  • Array.<number> — The values reordered to compensate the orientation.

getSliceGeometrySpacing( origins: Array.<Point3D>, ): number | undefined

Get the slice spacing from the difference in the Z directions of input origins.

Parameters

  • origins (Array.<Point3D>) — An array of Point3D.

Returns

  • number | undefined — The spacing.

getVolumeIdsForMerge( geometry: Geometry, volumeCount: number | undefined, ): Array.<VolumeId> | undefined

Volume ids to copy onto a merged geometry.

A geometry qualifies when it has one id per volume and that count is the merged volume count. Copying them keeps world positions (volume ids) convertible back to volume indices.

Parameters

  • geometry (Geometry) — The input geometry.
  • volumeCount (number | undefined) — The merged volume count.

Returns

  • Array.<VolumeId> | undefined — The ids to copy.

sameVolumeIds( ids0: Array.<VolumeId>, ids1: Array.<VolumeId>, ): boolean

Check that two volume id lists match.

Parameters

  • ids0 (Array.<VolumeId>) — The first list.
  • ids1 (Array.<VolumeId>) — The second list.

Returns

  • boolean — True when source, tag and value match in order.

mergeGeometries( geometry1: Geometry, geometry2: Geometry, ): Geometry

Merge two geometries into one using the merge size and smallest resolution. Volume ids are kept when one input defines them for the merged volume count, or both define the same ids. A 3D overlay then does not drop the 4D underlay volume index. WARNING: needs to be called with the final geometries.

Parameters

  • geometry1 (Geometry) — The first geometry.
  • geometry2 (Geometry) — The second geometry.

Returns

getSliceIndex( volumeGeometry: Geometry, sliceGeometry: Geometry, ): Index

Get the slice index of an input slice into a volume geometry.

Parameters

  • volumeGeometry (Geometry) — The volume geometry.
  • sliceGeometry (Geometry) — The slice geometry.

Returns

  • Index — The index of the slice in the volume geomtry.

getPaletteColourMap( dataElements: Record.<string, DataElement>, ): ColourMap | undefined

Get the palette colour map.

Parameters

  • dataElements (Record.<string, DataElement>) — The data elements.

Returns

  • ColourMap | undefined — The palette colour map.

getWindowPresets( dataElements: Record.<string, DataElement>, intensityFactor: number, ): Record.<string, WindowPreset> | undefined

Get the window level presets.

Parameters

  • dataElements (Record.<string, DataElement>) — The data elements.
  • intensityFactor (number) — The intensity factor.

Returns

  • Record.<string, WindowPreset> | undefined — The presets.

getFrameGeometry( dataElements: DataElements, frameNumber: number, ): Geometry

Get the geometry of one frame of a multi-frame data.

Frames with per-frame positions get their geometry from getSortedFramesGeometry: the frame position and the data time, or the volume index as time if frames share positions. Other frames are time frames: the frame geometry has the root position and the frame number as time. Once all frames are appended (see Image.appendSlice), the image has the same layout as the one created from the full buffer.

Parameters

  • dataElements (DataElements) — The DICOM tags.
  • frameNumber (number) — The frame number.

Returns

demoCreateImage(elements: Record.<string, DataElement>): Image

Demo Image creation from DICOM elements: takes elements and first element of the pixel buffer to create an image.

Warning: not to be used in production code.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

  • Image — The Image object.

simpleRange( dataAccessor: function, start: number, end: number, increment?: number, ): object

Get an simple iterator for a given range for a one component data.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols.

Parameters

  • dataAccessor (function) — Function to access data.
  • start (number) — The start of the range (included).
  • end (number) — The end of the range (excluded).
  • increment (number, optional) — The increment between indicies (default=1).

Returns

  • object — An iterator folowing the iterator and iterable protocol.

range( dataAccessor: function, start: number, maxIter: number, increment: number, blockMaxIter: number, blockIncrement: number, reverse1: boolean, reverse2: boolean, ): object

Get an iterator for a given range for a one component data.

Using 'maxIter' and not an 'end' index since it fails in some edge cases (for ex coronal2, ie zxy).

Parameters

  • dataAccessor (function) — Function to access data.
  • start (number) — Zero-based index at which to start the iteration.
  • maxIter (number) — The maximum number of iterations.
  • increment (number) — Increment between indicies.
  • blockMaxIter (number) — Number of applied increment after which blockIncrement is applied.
  • blockIncrement (number) — Increment after blockMaxIter is reached, the value is from block start to the next block start.
  • reverse1 (boolean) — If true, loop from end to start. WARN: don't forget to set the value of start as the last index!
  • reverse2 (boolean) — If true, loop from block end to block start.

Returns

  • object — An iterator folowing the iterator and iterable protocol.

rangeRegion( dataAccessor: function, start: number, end: number, increment: number, regionSize: number, regionOffset: number, ): object

Get an iterator for a given range with bounds (for a one component data).

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols.

Parameters

  • dataAccessor (function) — Function to access data.
  • start (number) — The start of the range (included).
  • end (number) — The end of the range (excluded).
  • increment (number) — The increment between indicies.
  • regionSize (number) — The size of the region to iterate through.
  • regionOffset (number) — The offset between regions.

Returns

  • object — An iterator folowing the iterator and iterable protocol.

rangeRegions( dataAccessor: function, start: number, end: number, increment: number, regions: Array.<Array.<number>>, ): object

Get an iterator for a given range with bounds (for a one component data).

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols.

Parameters

  • dataAccessor (function) — Function to access data.
  • start (number) — The start of the range (included).
  • end (number) — The end of the range (excluded).
  • increment (number) — The increment between indicies.
  • regions (Array.<Array.<number>>) — An array of regions: [off0, size, off1].

Returns

  • object — An iterator folowing the iterator and iterable protocol.

simpleRange3d( dataAccessor: function, start: number, end: number, increment: number, isPlanar: boolean, ): object

Get an iterator for a given range for a 3 components data.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols.

Parameters

  • dataAccessor (function) — Function to access data.
  • start (number) — The start of the range (included).
  • end (number) — The end of the range (excluded). (end - start) needs to be a multiple of 3...
  • increment (number) — The increment between indicies (default=1).
  • isPlanar (boolean) — A flag to know if the data is planar (RRRR...GGGG...BBBB...) or not (RGBRGBRGBRGB...), defaults to false.

Returns

  • object — A 3 components iterator folowing the iterator and iterable protocol, the value is an array of size 3 with each component.

range3d( dataAccessor: function, start: number, maxIter: number, increment: number, blockMaxIter: number, blockIncrement: number, reverse1: boolean, reverse2: boolean, isPlanar: boolean, ): object

Get an iterator for a given range for a 3 components data.

Using 'maxIter' and not an 'end' index since it fails in some edge cases (for ex coronal2, ie zxy).

Parameters

  • dataAccessor (function) — Function to access data.
  • start (number) — Zero-based index at which to start the iteration.
  • maxIter (number) — The maximum number of iterations.
  • increment (number) — Increment between indicies.
  • blockMaxIter (number) — Number of applied increment after which blockIncrement is applied.
  • blockIncrement (number) — Increment after blockMaxIter is reached, the value is from block start to the next block start.
  • reverse1 (boolean) — If true, loop from end to start. WARN: don't forget to set the value of start as the last index!
  • reverse2 (boolean) — If true, loop from block end to block start.
  • isPlanar (boolean) — A flag to know if the data is planar (RRRR...GGGG...BBBB...) or not (RGBRGBRGBRGB...), defaults to false.

Returns

  • object — An iterator folowing the iterator and iterable protocol.

getIteratorValues(iterator: object): Array

Get a list of values for a given iterator.

Parameters

  • iterator (object) — The iterator to use to loop through data.

Returns

  • Array — The list of values.

getSliceIterator( image: Image, index: Index, isRescaled: boolean, viewOrientation: Matrix33, ): object

Get a slice index iterator.

Parameters

  • image (Image) — The image to parse.
  • index (Index) — The current index.
  • isRescaled (boolean) — Flag for rescaled values (default false).
  • viewOrientation (Matrix33) — The view orientation.

Returns

  • object — The slice iterator.

getRegionSliceIterator( image: Image, index: Index, isRescaled: boolean, min: Point2D, max: Point2D, ): object

Get a slice index iterator for a rectangular region.

Parameters

  • image (Image) — The image to parse.
  • index (Index) — The current index.
  • isRescaled (boolean) — Flag for rescaled values (default false).
  • min (Point2D) — The minimum position (optional).
  • max (Point2D) — The maximum position (optional).

Returns

  • object — The slice iterator.

getVariableRegionSliceIterator( image: Image, index: Index, isRescaled: boolean, regions: Array.<Array.<Array.<number>>>, ): object | undefined

Get a slice index iterator for a rectangular region.

Parameters

  • image (Image) — The image to parse.
  • index (Index) — The current index.
  • isRescaled (boolean) — Flag for rescaled values (default false).
  • regions (Array.<Array.<Array.<number>>>) — An array of [x, y] pairs (min, max).

Returns

  • object | undefined — The slice iterator.

valueRange(values: Array, end: number): object

Get a multiple value iterator. The input array defines the values and their start index.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols.

Parameters

  • values (Array) — An array of {index, value} pairs.
  • end (number) — The end of the range (excluded).

Returns

  • object — An iterator folowing the iterator and iterable protocol.

generateGeometryMessage( imageSize: Size, imageSpacing: Spacing, ): object

Generate a worker message with geometry metadata only.

Parameters

  • imageSize (Size) — The image size.
  • imageSpacing (Spacing) — The image spacing.

Returns

  • object — The geometry part of a worker message.

generateWorkerMessage( imageBuffer: TypedArray, imageGeometry: Geometry, ): object

Generate a worker message to send to the labeling worker.

Parameters

  • imageBuffer (TypedArray) — The buffer to label.
  • imageGeometry (Geometry) — The image geometry.

Returns

  • object — The message to send to the worker.

buildLut(func: function): Array.<number>

Build a LUT of size lut_range_max.

Parameters

  • func (function) — The i to lut function.

Returns

  • Array.<number> — The LUT.

toMaxFirstThird(i: number): number

Ramp to lut_range_max minus one on the first third values.

Parameters

  • i (number) — The input index.

Returns

  • number — The lut value.

toMaxSecondThird(i: number): number

Ramp to lut_range_max minus one on the second third values, otherwise return 0 for the first third and lut_range_max minus one for the last third.

Parameters

  • i (number) — The input index.

Returns

  • number — The lut value.

toMaxThirdThird(i: number): number

Ramp to lut_range_max minus one on the last third values, otherwise return 0.

Parameters

  • i (number) — The input index.

Returns

  • number — The lut value.

id(i: number): number

Identity, returns i.

Parameters

  • i (number) — The input index.

Returns

  • number — The lut value.

invId(i: number): number

Returns lut_range_max minus one minus i.

Parameters

  • i (number) — The input index.

Returns

  • number — The lut value.

checkTag(dataElements: DataElements, tagDefinition: object)

Check that a DICOM tag definition is present in a parsed element.

Parameters

  • dataElements (DataElements) — The root dicom element.
  • tagDefinition (object) — The tag definition as {name, tag, type, enum}.

getDefaultDicomSegJson(): SimpleTagValues

Get the default DICOM seg tags as an object.

Returns

mergeMaskImages(mask1: MaskImage, mask2: MaskImage): MaskImage

Merge two mask images into a new combined mask image.

Segments from mask2 that share a segment number with mask1 are renumbered (bumped to the next available number) to avoid conflicts. Both masks must share the same spacing and orientation; the wider of the two geometries (the one with more slices) is used as the merged geometry, so a mask that only covers a sub-range of the other's slices does not get clipped. Brush-painted masks (no per-segment SegmentCollection data) are supported.

The returned image can be saved with the standard new MaskFactory().toDicom(merged, undefined, sourceImage) workflow.

Parameters

  • mask1 (MaskImage) — The first mask (provides meta).
  • mask2 (MaskImage) — The second mask to merge into mask1.

Returns

demoCreateMaskImage( elements: Record.<string, DataElement>, ): MaskImage

Demo mask Image creation from DICOM elements: takes elements and first element of the pixel buffer to create an image.

Warning: not to be used in production code.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.

Returns

isLutBitsStored(bitsStored: number): boolean

Check if a pre-computed LUT can be created for the input bits stored.

Parameters

  • bitsStored (number) — The number of bits used to store the data.

Returns

  • boolean — True if a LUT can be created.

generateWorkerMessages( sourceImageBuffer: TypedArray, sourceImageGeometry: Geometry, targetImageGeometry: Geometry, pixelRepresentation: number, interpolated: boolean, jobId: string, ): Array.<object>

Generate a worker message to send to the resampling worker.

Parameters

  • sourceImageBuffer (TypedArray) — The buffer to resample.
  • sourceImageGeometry (Geometry) — The current image geometry.
  • targetImageGeometry (Geometry) — The geometry to resample to.
  • pixelRepresentation (number) — The pixel representation of the source image.
  • interpolated (boolean) — If true use bilinear sampling, otherwise use nearest neighbor.
  • jobId (string) — Unique resampling job id.

Returns

  • Array.<object> — The message to send to the worker.

generateResampledGeometry( sourceImageGeometry: Geometry, targetOrientation: Matrix33, centerOfRotation: Point | undefined, ): Geometry

Generate the geometry of the resampled image.

Parameters

  • sourceImageGeometry (Geometry) — The current image geometry.
  • targetOrientation (Matrix33) — The target image orientation.
  • centerOfRotation (Point | undefined) — World space center of rotation.

Returns

generateBuffer( sourceImageBuffer: TypedArray, targetSize: Size, ): TypedArray

Generate the buffer for the resampled image.

Parameters

  • sourceImageBuffer (TypedArray) — The current image buffer.
  • targetSize (Size) — The size of the target.

Returns

getReferencedFrameOfReferenceUIDFromRTStruct( dataElements: Record.<string, DataElement>, ): string | undefined

Get the referenced frame of reference UID from an RT Structure Set.

Path: ReferencedFrameOfReferenceSequence (3006,0010) → FrameOfReferenceUID (0020,0052), first item.

Ref: https://dicom.nema.org/medical/dicom/2024a/output/chtml/part03/sect_C.8.8.5.html.

Parameters

  • dataElements (Record.<string, DataElement>) — The data elements.

Returns

  • string | undefined — The frame of reference UID.

getDefaultDicomRTStructJson(): SimpleTagValues

Get the default DICOM RT Structure Set tags as an object.

Returns

bfsMarkVisited( buffer: Uint8Array, sliceOffset: number, width: number, height: number, value: number, startIdx: number, visited: Uint8Array, )

BFS (Breadth-First Search) flood-fill: mark all 8-connected pixels with value as visited.

Parameters

  • buffer (Uint8Array) — The mask buffer.
  • sliceOffset (number) — Byte offset of the slice in buffer.
  • width (number) — Slice width.
  • height (number) — Slice height.
  • value (number) — Segment value.
  • startIdx (number) — Flat index of the seed pixel.
  • visited (Uint8Array) — Per-slice visited flags (length = width*height).

mooreBoundary( buffer: Uint8Array, sliceOffset: number, width: number, height: number, value: number, sx: number, sy: number, ): Array.<{x: number, y: number}>

Trace the outer boundary of a connected foreground region using Moore neighborhood tracing (Jacob's stopping criterion).

Parameters

  • buffer (Uint8Array) — The mask buffer.
  • sliceOffset (number) — Byte offset of the slice in buffer.
  • width (number) — Slice width.
  • height (number) — Slice height.
  • value (number) — Segment value.
  • sx (number) — X of the top-left pixel of the component.
  • sy (number) — Y of the top-left pixel of the component.

Returns

  • Array.<{x: number, y: number}> — Ordered boundary vertices.

bufferToPolygons( buffer: Uint8Array, sliceOffset: number, width: number, height: number, value: number, ): Array.<Array.<{x: number, y: number}>>

Extract polygon contours from a mask slice using Moore neighborhood tracing. Returns one polygon per connected region with the given segment value.

Parameters

  • buffer (Uint8Array) — The mask buffer (all slices).
  • sliceOffset (number) — Byte offset of the slice in buffer.
  • width (number) — Slice width in pixels.
  • height (number) — Slice height in pixels.
  • value (number) — Segment value to trace.

Returns

  • Array.<Array.<{x: number, y: number}>> — One polygon per connected region.

ptSegDist(pt: Object, a: Object, b: Object): number

Perpendicular distance from a point to the line through a and b.

Parameters

  • pt (Object) — The point.
  • a (Object) — Line start.
  • b (Object) — Line end.

Returns

  • number — Distance in pixels.

simplifyPolygon( pts: Array.<{x: number, y: number}>, epsilon: number, ): Array.<{x: number, y: number}>

Simplify a polygon using the Ramer-Douglas-Peucker algorithm. Ref: https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm.

Parameters

  • pts (Array.<{x: number, y: number}>) — Input vertices.
  • epsilon (number) — Max allowed deviation in pixels.

Returns

  • Array.<{x: number, y: number}> — Simplified vertices.

fillPolygons( buffer: Uint8Array, sliceOffset: number, width: number, height: number, polygonsList: Array.<Array.<{x: number, y: number}>>, value: number, )

Fill one or more closed polygons into a flat Uint8Array slice using a scanline even-odd rule applied across all of their edges together. Passing an outer contour together with a nested inner contour therefore punches a hole where the inner contour lies, matching how DICOM CLOSEDPLANAR_XOR (and, by convention, plain CLOSED_PLANAR) contours on the same ROI/slice combine (see PS3.3 C.8.8.6). Ref: https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule.

Parameters

  • buffer (Uint8Array) — The mask buffer (all slices).
  • sliceOffset (number) — Byte offset of the current slice in buffer.
  • width (number) — Slice width in pixels.
  • height (number) — Slice height in pixels.
  • polygonsList (Array.<Array.<{x: number, y: number}>>) — Polygons (outer and/or hole contours) in pixel coords, filled together.
  • value (number) — Segment number to write.

markOutsideBackground( buffer: Uint8Array, sliceOffset: number, width: number, height: number, value: number, ): Uint8Array

Flood-fill background pixels reachable from the slice border without crossing any value-valued foreground pixel. Used to tell apart plain outside background from background fully enclosed by foreground (holes).

Parameters

  • buffer (Uint8Array) — The mask buffer (all slices).
  • sliceOffset (number) — Byte offset of the slice in buffer.
  • width (number) — Slice width in pixels.
  • height (number) — Slice height in pixels.
  • value (number) — Segment value to treat as foreground.

Returns

  • Uint8Array — Per-slice flags, 1 where reachable from the border.

findHolePolygons( buffer: Uint8Array, sliceOffset: number, width: number, height: number, value: number, ): Array.<Array.<{x: number, y: number}>>

Find polygons for background regions fully enclosed by value-valued foreground (ie holes), traced the same way as foreground regions.

Parameters

  • buffer (Uint8Array) — The mask buffer (all slices).
  • sliceOffset (number) — Byte offset of the slice in buffer.
  • width (number) — Slice width in pixels.
  • height (number) — Slice height in pixels.
  • value (number) — Segment value to trace holes for.

Returns

  • Array.<Array.<{x: number, y: number}>> — One polygon per enclosed hole region.

computeGreyscale( data: Array, width: number, height: number, ): object

Compute grey scale.

Parameters

  • data (Array) — The input data.
  • width (number) — The width of the output.
  • height (number) — The height of the output.

Returns

  • object — A greyscale object.

computeGradient(greyscale: object): object

Compute gradient.

Parameters

  • greyscale (object) — The input greyscale.

Returns

  • object — A gradient object.

computeLaplace(greyscale: object): object

Parameters

  • greyscale (object) — The input greyscale.

Returns

  • object — A laplace object.

computeGradX(greyscale: object): Array

Compute the X gradient.

Parameters

  • greyscale (object) — The values.

Returns

  • Array — The gradient.

computeGradY(greyscale: object): Array

Compute the Y gradient.

Parameters

  • greyscale (object) — The values.

Returns

  • Array — The gradient.

gradUnitVector( gradX: Array, gradY: Array, px: number, py: number, out: object, )

Compute the gradient unit vector.

Parameters

  • gradX (Array) — The X gradient.
  • gradY (Array) — The Y gradient.
  • px (number) — The point X.
  • py (number) — The point Y.
  • out (object) — The result.

gradDirection( gradX: Array, gradY: Array, px: number, py: number, qx: number, qy: number, ): number

Compute the gradient direction.

Parameters

  • gradX (Array) — The X gradient.
  • gradY (Array) — The Y gradient.
  • px (number) — The point X.
  • py (number) — The point Y.
  • qx (number) — The q X.
  • qy (number) — The q Y.

Returns

  • number — The direction.

computeSides( dist: number, gradX: Array, gradY: Array, greyscale: object, ): object

Compute the sides.

Parameters

  • dist (number) — The distance.
  • gradX (Array) — The X gradient.
  • gradY (Array) — The Y gradient.
  • greyscale (object) — The value.

Returns

  • object — The sides.

gaussianBlur(buffer: Array, out: Array)

Gaussian blur an input buffer.

Parameters

  • buffer (Array) — The input buffer.
  • out (Array) — The result.

createRoiSliceBuffers( imageBuffer: Uint8Array, segmentNumbers: Array.<number>, sliceSize: number, sliceOffset: number, ): Record.<number, Uint8Array>

Create ROI slice buffers.

Parameters

  • imageBuffer (Uint8Array) — The mask image buffer.
  • segmentNumbers (Array.<number>) — The mask segment numbers.
  • sliceSize (number) — The size of a slice.
  • sliceOffset (number) — The slice offset.

Returns

  • Record.<number, Uint8Array> — The ROI slice image buffers, indexed by segment index (segment.number - 1).

createRoiBuffers( imageBuffer: Uint8Array, geometry: Geometry, segmentNumbers: Array.<number>, ): Record.<string, Record.<number, Uint8Array>>

Create ROI buffers.

Parameters

  • imageBuffer (Uint8Array) — The mask image buffer.
  • geometry (Geometry) — The mask geometry.
  • segmentNumbers (Array.<number>) — The mask segment numbers.

Returns

  • Record.<string, Record.<number, Uint8Array>> — The ROI buffers, indexed by segment index (segment.number - 1) and slice index.

demoCreateView( elements: Record.<string, DataElement>, image: Image, ): View

Demo View creation from DICOM elements and image.

Warning: not to be used in production code.

Parameters

  • elements (Record.<string, DataElement>) — The DICOM elements.
  • image (Image) — The associated image.

Returns

  • View — The View object.

generateImageDataMonochrome( array: ImageData, iterator: object, alphaFunc: function, windowLut: WindowLut, colourMap: ColourMap, )

Generate image data for 'MONOCHROME*' photometric interpretation.

Parameters

  • array (ImageData) — The array to store the outut data.
  • iterator (object) — Position iterator.
  • alphaFunc (function) — The alpha function.
  • windowLut (WindowLut) — The window/level LUT.
  • colourMap (ColourMap) — The colour map.

generateImageDataPaletteColor( array: ImageData, iterator: object, alphaFunc: function, colourMap: ColourMap, is16BitsStored: boolean, )

Generate image data for 'PALETTE COLOR' photometric interpretation.

Parameters

  • array (ImageData) — The array to store the outut data.
  • iterator (object) — Position iterator.
  • alphaFunc (function) — The alpha function.
  • colourMap (ColourMap) — The colour map.
  • is16BitsStored (boolean) — Flag to know if the data is 16bits.

generateImageDataPaletteColorBlend( array: ImageData, iterator: object, colourMap: ColourMap, collection: SegmentCollection, sliceSize: number, imageSize: Size, orientation: Matrix33, contourThickness: number, fillOpacity: number, segmentViewHelper?: MaskSegmentViewHelper, )

Generate image data for 'PALETTE COLOR' with overlapping segment blend. For each pixel, averages the palette colours of all visible segments present at that buffer offset.

Contour detection uses a cached union ImageContour (one binary buffer where any visible segment is present) built by SegmentCollection. This avoids false seams that would occur if the label-map ImageContour were used, because the label map stores only first-wins values at overlap positions.

Parameters

  • array (ImageData) — The array to store the output data.
  • iterator (object) — Position iterator.
  • colourMap (ColourMap) — The colour map.
  • collection (SegmentCollection) — The segment collection.
  • sliceSize (number) — Number of pixels per slice (ncols * nrows).
  • imageSize (Size) — The full image size.
  • orientation (Matrix33) — The view orientation.
  • contourThickness (number) — Contour thickness (0 = fill only).
  • fillOpacity (number) — Fill opacity [0-1].
  • segmentViewHelper (MaskSegmentViewHelper, optional) — Hidden-segment tracker.

generateImageDataRgb( array: ImageData, iterator: object, alphaFunc: function, )

Generate image data for 'RGB' photometric interpretation.

Parameters

  • array (ImageData) — The array to store the outut data.
  • iterator (object) — Position iterator.
  • alphaFunc (function) — The alpha function.

generateImageDataYbrFull( array: ImageData, iterator: object, alphaFunc: function, )

Generate image data for 'YBR_FULL' photometric interpretation.

Parameters

  • array (ImageData) — The array to store the outut data.
  • iterator (object) — Position iterator.
  • alphaFunc (function) — The alpha function.

equalWl(wl0: WindowLevel, wl1: WindowLevel): boolean

Check for window level equality.

Parameters

Returns

  • boolean — True if both objects are equal.

getMinWindowWidth(voiLutFunctionName?: string): number

Get the minimum window width allowed by a VOI LUT function: LINEAR requires a width of at least 1, LINEAR_EXACT and SIGMOID require a strictly positive width (the epsilon avoids a division by zero).

Ref: https://dicom.nema.org/medical/dicom/2024a/output/chtml/part03/sect_C.11.2.html#sect_C.11.2.1.

Parameters

  • voiLutFunctionName (string, optional) — The VOI LUT function name, defaults to 'LINEAR'.

Returns

  • number — The minimum window width.

validateWindowLevel( wl: WindowLevel, range: object, voiLutFunctionName?: string, ): WindowLevel | undefined

Validate and constrain an input window level.

Parameters

  • wl (WindowLevel) — The window level to validate.
  • range (object) — The image pixel data range.
  • voiLutFunctionName (string, optional) — The VOI LUT function name, defaults to 'LINEAR'.

Returns

getLoaderList(): Array

Get the list of available data-loader constructors. Always returns the same array instance so callers can mutate it (for example in tests) and have those mutations visible to all consumers.

Returns

  • Array — The list of loader constructors.

mulABC(a: number, b: number, c: number): number

Mulitply the three inputs if the last two are not null.

Parameters

  • a (number) — The first input.
  • b (number) — The second input.
  • c (number) — The third input.

Returns

  • number — The multiplication of the three inputs or null if one of the last two is null.

mulABC(a: number, b: number, c: number): number

Mulitply the three inputs if the last two are not null.

Parameters

  • a (number) — The first input.
  • b (number) — The second input.
  • c (number) — The third input.

Returns

  • number — The multiplication of the three inputs or null if one of the last two is null.

getEllipseIndices( center: Index, radius: Array.<number>, dir: Array.<number>, ): Array.<Index>

Get the indices that form a ellpise.

Parameters

  • center (Index) — The ellipse center.
  • radius (Array.<number>) — The 2 ellipse radiuses.
  • dir (Array.<number>) — The 2 ellipse directions.

Returns

  • Array.<Index> — The indices of the ellipse.

getEntriesValueAt( entries: Array.<HistogramEntry>, index: number, ): number

Get the value at a given index of the sorted list of values that the entries describe.

Parameters

  • entries (Array.<HistogramEntry>) — The sorted entries.
  • index (number) — The index in the sorted list of values.

Returns

  • number — The value.

getEntriesPercentile( entries: Array.<HistogramEntry>, total: number, ratio: number, ): number

Get the percentile of the values that the entries describe. Uses linear interpolation between values like getPercentile in math/stats.js.

Parameters

  • entries (Array.<HistogramEntry>) — The sorted entries.
  • total (number) — The total count.
  • ratio (number) — The percentile ratio [0-1].

Returns

  • number — The percentile.

getZeroIndex(size: number): Index

Get an index with values set to 0 and the input size.

Parameters

  • size (number) — The size of the index.

Returns

  • Index — The zero index.

getAngle(line0: Line, line1: Line): number

Get the angle between two lines in degree.

Parameters

  • line0 (Line) — The first line.
  • line1 (Line) — The second line.

Returns

  • number — The angle.

areOrthogonal(line0: Line, line1: Line): boolean

Check if two lines are orthogonal.

Parameters

  • line0 (Line) — The first line.
  • line1 (Line) — The second line.

Returns

  • boolean — True if both lines are orthogonal.

isPointInLineRange(point: Point2D, line: Line): boolean

Check if a point is in a line coordinate range.

Parameters

  • point (Point2D) — The input point.
  • line (Line) — The input line.

Returns

  • boolean — True if the input point is in the line coordinate range.

getDistanceToSegment( point: Point2D, begin: Point2D, end: Point2D, ): number

Get the distance between a point and a line segment.

Parameters

  • point (Point2D) — The input point.
  • begin (Point2D) — The segment begin point.
  • end (Point2D) — The segment end point.

Returns

  • number — The distance to the closest point of the segment.

getPerpendicularLine( line: Line, point: Point2D, length: number, spacing?: Scalar2D, ): Line

Get a perpendicular line to an input one at a given point.

Parameters

  • line (Line) — The line to be perpendicular to.
  • point (Point2D) — The middle point of the perpendicular line.
  • length (number) — The length of the perpendicular line.
  • spacing (Scalar2D, optional) — Optional image spacing, default to [1,1].

Returns

  • Line — The perpendicular line.

getPerpendicularLineAtDistance( line: Line, distance: number, length: number, spacing?: Scalar2D, ): Line

Get a perpendicular line to an input one at a given distance of its begin point.

Parameters

  • line (Line) — The line to be perpendicular to.
  • distance (number) — The distance to the input line begin point.
  • length (number) — The length of the perpendicular line.
  • spacing (Scalar2D, optional) — Optional image spacing, default to [1,1].

Returns

  • Line — The perpendicular line.

getLineFromEquation( slope: number, intercept: number, point: Point2D, length: number, spacing?: Scalar2D, ): Line

Get a line from an equation, a middle point and a length.

Parameters

  • slope (number) — The line slope.
  • intercept (number) — The line intercept.
  • point (Point2D) — The middle point of the line.
  • length (number) — The line length.
  • spacing (Scalar2D, optional) — Optional image spacing, default to [1,1].

Returns

  • Line — The resulting line.

getMatrixInverse(m: Matrix33): Matrix33 | undefined

Get the inverse of an input 3*3 matrix.

Ref:

Parameters

Returns

  • Matrix33 | undefined — The inverse matrix or undefined if the determinant is zero.

getIdentityMat33(): Matrix33

Create a 3x3 identity matrix.

Returns

isIdentityMat33(mat33: Matrix33): boolean

Check if a matrix is a 3x3 identity matrix.

Parameters

  • mat33 (Matrix33) — The matrix to test.

Returns

  • boolean — True if identity.

isSimilar(a: number, b: number, tol?: number): boolean

Check if two numbers are similar.

Parameters

  • a (number) — The first number.
  • b (number) — The second number.
  • tol (number, optional) — Optional comparison tolerance, defaults to Number.EPSILON.

Returns

  • boolean — True if similar.

isAboveEpsilon(value: number): boolean

Check if a value is above REAL_WORLD_EPSILON100 meaning it is non negligible. Warns if the value is above REAL_WORLD_EPSILON but below REAL_WORLD_EPSILON100.

Parameters

  • value (number) — The value to test.

Returns

  • boolean — True if the value is above the REAL_WORLD_EPSILON*100, false otherwise.

precisionRound(number: number, precision: number): number

Round a float number to a given precision.

Inspired from https://stackoverflow.com/a/49729715/3639892.

toPrecision uses all non zero digits of the number: (123.009).toPrecision(4) = "123.0"; (0.09).toPrecision(4) = "0.09000".

toFixed does not always behave as expected: (123.009).toFixed(2) = "123.01"; (0.009).toFixed(2) = "0.01"; but (-0.005).toFixed(2) = "-0.01" (expecting 0); (1.005).toFixed(2) = "1" (expecting 1.01).

Parameters

  • number (number) — The number to round.
  • precision (number) — The rounding precision, ie the result number of digits after the comma.

Returns

  • number — The rounded number.

getCoronalMat33(): Matrix33

Create a 3x3 coronal (xzy) matrix.

Returns

getSagittalMat33(): Matrix33

Create a 3x3 sagittal (yzx) matrix.

Returns

getMatrixFromName(name: string): Matrix33 | undefined

Get an orientation matrix from a name.

Parameters

  • name (string) — The orientation name.

Returns

  • Matrix33 | undefined — The orientation matrix.

getOrientationStringLPS(matrix: Matrix33): string

Get the orientation code of an orientation matrix. Each letter defines the towards direction. Letters are: R (right), L (left), A (anterior), P (posterior), I (inferior) and S (superior).

Parameters

  • matrix (Matrix33) — The orientation matrix.

Returns

  • string — The orientation code.

getVectorStringLPS(vector: Vector3D): string

Get the orientation code of an orientation vector. Credits: David Clunie, https://www.dclunie.com/medical-image-faq/html/part2.html.

Parameters

  • vector (Vector3D) — The orientation vector.

Returns

  • string — The orientation code.

getLPSGroup(code: string): string | undefined

Get the LPS 'group' (axial, coronal or sagittal) from a LPS code.

Parameters

  • code (string) — The LPS code string.

Returns

  • string | undefined — The group.

getOrientationName(cosines: Array.<number>): string | undefined

Get the name of an image orientation patient.

Parameters

  • cosines (Array.<number>) — The image orientation patient cosines (6 values).

Returns

  • string | undefined — The orientation name: axial, coronal or sagittal.

getOrientationFromCosines( cosines: Array.<number>, ): Matrix33 | undefined

Get the orientation matrix associated to the direction cosines.

Parameters

  • cosines (Array.<number>) — The image orientation patient cosines (6 values).

Returns

  • Matrix33 | undefined — The orientation matrix.

getCosinesFromOrientation(matrix: Matrix33): Array.<number>

Get the direction cosines from an orientation matrix.

Parameters

  • matrix (Matrix33) — The input matrix.

Returns

  • Array.<number> — The image orientation patient cosines (6 values).

getViewOrientation( imageOrientation: Matrix33, targetOrientation: Matrix33, ): Matrix33

Get the view orientation according to an image and target orientation. The view orientation is used to go from target to image space.

Parameters

  • imageOrientation (Matrix33) — The image geometry.
  • targetOrientation (Matrix33) — The target orientation.

Returns

getTargetOrientation( imageOrientation: Matrix33, viewOrientation: Matrix33, ): Matrix33

Get the target orientation according to an image and view orientation. The target orientation is used to go from target to real space.

Parameters

  • imageOrientation (Matrix33) — The image geometry.
  • viewOrientation (Matrix33) — The view orientation.

Returns

getLegacyTargetOrientation( imageOrientation: Matrix33, targetOrientation: Matrix33, ): Matrix33

Get the legacy target orientation: the target orientation as it was before v0.37, with an abs for coronal acquisitions. Only used to recognise the plane cosines (planePoints) of annotations saved with previous versions.

Parameters

  • imageOrientation (Matrix33) — The image orientation.
  • targetOrientation (Matrix33) — The target orientation, see getTargetOrientation.

Returns

  • Matrix33 — The legacy target orientation.

getDisplayOrientation( imageOrientation: Matrix33, targetName?: string, ): Matrix33

Get the display orientation of a view: the orientation matrix of the target orientation name or, if undefined or unknown, the one of the image acquisition plane.

Parameters

  • imageOrientation (Matrix33) — The image orientation.
  • targetName (string, optional) — The target orientation name.

Returns

getViewFlips( imageOrientation: Matrix33, displayOrientation: Matrix33, targetOrientation: Matrix33, ): Object

Get the layer flips needed to show an image with its display orientation: for each view axis, flip it if its direction is opposite to the display one.

The scale flips are in the target space, as expected by the layers flipScale methods, and the offset ones in the view space.

Parameters

  • imageOrientation (Matrix33) — The image orientation.
  • displayOrientation (Matrix33) — The display orientation, see getDisplayOrientation.
  • targetOrientation (Matrix33) — The layers target orientation, see getTargetOrientation.

Returns

  • Object — The scale and offset flips.

getEqualPoint3DFunction(point: Point3D): function

Get an array find callback for an equal input point.

Parameters

  • point (Point3D) — The point to compare to.

Returns

  • function — A function that compares, using equals, its input point to the one given as input to this function.

includesPoint3D(arr: Array.<Point3D>, val: Point3D): boolean

Check if an array of Point3D includes a given one.

Parameters

  • arr (Array.<Point3D>) — The array of Point3D.
  • val (Point3D) — The Point3D to look for.

Returns

  • boolean — True if included.

point3DFromArray(arr: Array.<number>): Point3D

Create a Point3D from an array.

Parameters

  • arr (Array.<number>) — The input array.

Returns

mulABC(a: number, b: number, c: number): number

Mulitply the three inputs if the last two are not null.

Parameters

  • a (number) — The first input.
  • b (number) — The second input.
  • c (number) — The third input.

Returns

  • number — The multiplication of the three inputs or null if one of the last two is null.

getRectangleIndices( center: Index, size: Array.<number>, dir: Array.<number>, ): Array.<Index>

Get the indices that form a rectangle.

Parameters

  • center (Index) — The rectangle center.
  • size (Array.<number>) — The 2 rectangle sizes.
  • dir (Array.<number>) — The 2 rectangle directions.

Returns

  • Array.<Index> — The indices of the rectangle.

getStats( values: Array.<number>, flags?: Array.<string>, ): Statistics | undefined

Get statistics on an input array of number. Note: could use https://github.com/tmcw/simple-statistics.

Parameters

  • values (Array.<number>) — The array of values to extract stats from.
  • flags (Array.<string>, optional) — A list of stat value names to calculate.

Returns

  • Statistics | undefined — A statistics object, undefined if the input array is empty.

includesFullStatsFlags(flags?: Array.<string>): boolean

Does the input flag list contain a full stat element?

Parameters

  • flags (Array.<string>, optional) — A list of stat values to calculate.

Returns

  • boolean — True if one of the flags is a full stat flag.

getBasicStats(values: Array.<number>): Statistics | undefined

Get simple stats: minimum, maximum, mean and standard deviation of an array of values.

Parameters

  • values (Array.<number>) — The array of values to extract stats from.

Returns

  • Statistics | undefined — Simple statistics (no median, p25 nor p75), undefined if the input array is empty.

getFullStats(values: Array.<number>): Statistics | undefined

Get full stats: minimum, maximum, mean, standard deviation, median, 25% and 75% percentile of an array of values.

Parameters

  • values (Array.<number>) — The array of values to extract stats from, left unchanged.

Returns

  • Statistics | undefined — Complete statistics (includes median, p25 and p75), undefined if the input array is empty.

getPercentile(values: Array.<number>, ratio: number): number

Get an arrays' percentile. Uses linear interpolation for percentiles that lie between data points. See: https://en.wikipedia.org/wiki/Percentile (second variant interpolation).

Parameters

  • values (Array.<number>) — The sorted array of values.
  • ratio (number) — The percentile ratio [0-1].

Returns

  • number — The percentile.

guid(): string

Unique ID generator.

See http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript and this answer.

Returns

  • string — A unique ID.

getIndexCompareFunction(direction: number): object

Get an array sort callback:

  • f(a,b) > 0 -> b,a,
  • f(a,b) < 0 -> a,b,
  • f(a,b) = 0 -> original order.

Parameters

  • direction (number) — The direction to use to compare indices.

Returns

  • object — A function that compares two Index.

getDimensionOrganization(): object

Get a dimension organisation used to index a DICOM seg.

Returns

  • object — The indices and organisations.

getCircleIndices( geometry: Geometry, position: Point, radiuses: Array.<number>, dims: Array.<number>, ): Array.<Index>

Get the indices that form a circle. Can be an ellipse to adapt to view.

Parameters

  • geometry (Geometry) — The geometry.
  • position (Point) — The circle center.
  • radiuses (Array.<number>) — The circle radiuses.
  • dims (Array.<number>) — The 2 dimensions.

Returns

  • Array.<Index> — The indices of the circle.

getOriginIndexRangeFromMaskIndices( geometry: Geometry, indices: Array.<Index>, ): Array.<number>

Get the range of origin indices that correspond to input new mask indices.

Parameters

  • geometry (Geometry) — The geometry.
  • indices (Array.<Index>) — An array of indices.

Returns

  • Array.<number> — Range of indices in the input origins.

getOffsetsFromIndices( geometry: Geometry, indices: Array.<Index>, ): Array.<number>

Get the data offsets that correspond to input indices.

Parameters

  • geometry (Geometry) — The geometry.
  • indices (Array.<Index>) — An array of indices.

Returns

  • Array.<number> — An array of offsets.

formatString(template: *, ...values: any): string

Parameters

  • template (*) — The template where to add values.
  • values (any) — The values to add to the template.

Returns

  • string — The formated string.

normalizeThreshold(threshold: Scalar2D | undefined): Scalar2D

Parameters

  • threshold (Scalar2D | undefined) — Raw threshold.

Returns

  • Scalar2D — Copy with numeric x and y.

isValidDrawPoint( point: Point2D, layerGroup: LayerGroup, ): boolean

Check if a point is valid in the input layerGroup active draw layer.

Parameters

  • point (Point2D) — The display point to validate.
  • layerGroup (LayerGroup) — The layer group.

Returns

  • boolean — True if valid.

getActiveOrFirstMonochromeViewLayer( layerGroup: LayerGroup, activeViewLayerOnly: boolean, ): ViewLayer | undefined

Active view layer, or the first monochrome view layer among active layers when activeViewLayerOnly is false (window/level-style resolution).

Parameters

  • layerGroup (LayerGroup) — The layer group.
  • activeViewLayerOnly (boolean) — If true, use LayerGroup#getActiveViewLayer only; if false, the first layer whose view controller reports monochrome.

Returns

getActiveOrDrawRefViewLayer( layerGroup: LayerGroup, ): ViewLayer | undefined

Active view layer, or the view layer referenced by the active draw layer.

Parameters

Returns

getSpinY(event: object): number

Get a normalised spin speed in the Y direction to try to support trackpads (small and large deltaY) and mouse wheel (large deltaY). Should return 1 or -1 for a single mouse wheel tick.

Parameters

  • event (object) — The wheel event.

Returns

  • number — The normalised spin Y.

isNodeNameLabel(node: Konva.Node): boolean

Is an input node's name 'label'.

Parameters

  • node (Konva.Node) — A Konva node.

Returns

  • boolean — True if the node's name is 'label'.

isNodeNameShape(node: Konva.Node): boolean

Is an input node's name 'shape'.

Parameters

  • node (Konva.Node) — A Konva node.

Returns

  • boolean — True if the node's name is 'shape'.

isPositionNode(node: Konva.Node): boolean

Is an input node a position node.

Parameters

  • node (Konva.Node) — A Konva node.

Returns

  • boolean — True if the node's name is 'position-group'.

getLineShape(group: Konva.Group): Konva.Line | undefined

Get a Konva.Line shape from a group.

Parameters

  • group (Konva.Group) — The group to look into.

Returns

  • Konva.Line | undefined — The shape.

getAnchorShape( group: Konva.Group, index: number, ): Konva.Ellipse | undefined

Get a Konva.Ellipse anchor shape from a group.

Parameters

  • group (Konva.Group) — The group to look into.
  • index (number) — The anchor index.

Returns

  • Konva.Ellipse | undefined — The anchor shape.

isNodeWithId(id: string): testFn

Get a lambda to check a node's id.

Parameters

  • id (string) — The id to check.

Returns

  • testFn — A function to check a node's id.

getDefaultAnchor( x: number, y: number, id: string, style: Style, ): Konva.Ellipse

Get the default anchor shape.

Parameters

  • x (number) — The X position.
  • y (number) — The Y position.
  • id (string) — The shape id.
  • style (Style) — The application style.

Returns

  • Konva.Ellipse — The default anchor shape.

getAnchorIndex(id: string): number

Get an anchor index from its id.

Parameters

  • id (string) — The anchor id as 'anchor#'.

Returns

  • number — The anchor index.

boundNodePosition( node: Konva.Node, min: Point2D, max: Point2D, ): boolean

Bound a node position.

Parameters

  • node (Konva.Node) — The node to bound the position.
  • min (Point2D) — The minimum position.
  • max (Point2D) — The maximum position.

Returns

  • boolean — True if the position was corrected.

getShapePositionRange( stageSize: Scalar2D, shape: Konva.Shape, ): object

Get a shape top left position range.

Parameters

  • stageSize (Scalar2D) — The stage size as {x,y}.
  • shape (Konva.Shape) — The shape to evaluate.

Returns

  • object — The range as {min, max}.

isShapeInRange( shape: Konva.Shape, min: Point2D, max: Point2D, ): boolean

Is an input shape top left position in the input range.

Parameters

  • shape (Konva.Shape) — The shape to evaluate.
  • min (Point2D) — The minimum top left position.
  • max (Point2D) — The maximum top left position.

Returns

  • boolean — True if in range.

validateAnchorPosition( stageSize: Scalar2D, anchor: Konva.Shape, ): boolean

Validate an anchor position.

Parameters

  • stageSize (Scalar2D) — The stage size {x,y}.
  • anchor (Konva.Shape) — The anchor to evaluate.

Returns

  • boolean — True if the position was corrected.

defaultOpenRoiDialog(annotation: Annotation, callback: function)

Open a dialogue to edit roi data. Defaults to window.prompt.

Parameters

  • annotation (Annotation) — The roi data.
  • callback (function) — The callback to launch on dialogue exit.

setLineHitFunc( kline: Konva.Line, line: Line, zoomScale: Scalar2D, hitWidth?: number, )

Apply a wider quadrilateral hit area to an open Konva.Line.

The hit zone is a rectangle whose sides are the perpendicular half-widths drawn at each endpoint of the line. This makes thin lines much easier to click without changing their visual appearance.

Parameters

  • kline (Konva.Line) — The Konva line shape to update.
  • line (Line) — The mathematical line (provides begin/end points).
  • zoomScale (Scalar2D) — The current zoom scale {x, y}.
  • hitWidth (number, optional) — Half-width of the hit quad in pixels (default 20).

getDefaultLabel(name: string): object

Get the label text expression for a named shape, honouring the custom label override when one is set.

Parameters

  • name (string) — The shape name.

Returns

  • object — The label text expression object.

protractorArcParams(protractor: object): Object

Compute the arc parameters for a complete protractor.

Parameters

  • protractor (object) — The Protractor math shape.

Returns

  • Object — Params.

buildProtractorArc( protractor: object, colour: string, style: Style, ): Konva.Arc

Build the arc Konva node for a protractor.

Parameters

  • protractor (object) — The Protractor math shape.
  • colour (string) — The stroke colour.
  • style (Style) — The drawing style.

Returns

  • Konva.Arc — The arc node.

applyProtractorHitFunc(kshape: Konva.Line, protractor: object)

Apply the triangle hit area to the protractor's Konva.Line shape.

Parameters

  • kshape (Konva.Line) — The Konva line node.
  • protractor (object) — The Protractor math shape.

getPainter(name: string): KonvaShapePainter

Get the Konva shape entry for a factory name.

Parameters

  • name (string) — The factory / annotator name.

Returns

toStringId(arr: Array, dims?: Array.<number>): string

Get a string id from array values in the form of: '#0-1_#1-2'.

Parameters

  • arr (Array) — The input array.
  • dims (Array.<number>, optional) — Optional list of dimensions to use.

Returns

  • string — The string id.

getArrayFromStringId(inputStr: string): Array

Get an array from an id string in the form of: '#0-1_#1-2' (result of toStringId).

Parameters

  • inputStr (string) — The input string.

Returns

  • Array — The corresponding array (minimum size is 3D).

checkAndApply(a: any, b: any, func: function): any

Apply an input 'compare'function after having checked the two inputs for undefined.

Parameters

  • a (any) — The first input.
  • b (any) — The second input.
  • func (function) — The compare function.

Returns

  • any — The result of the function applied to the inputs or the not undefined input.

arrayMap(arr0: Array, arr1: Array, func: function): Array

Apply an input 'compare' function to items of 2 arrays. The output will have a length that is the maximum of both inputs.

Parameters

  • arr0 (Array) — The first array.
  • arr1 (Array) — The second array.
  • func (function) — The compare function.

Returns

  • Array — The result array.

arrayContains( arr0: Array.<string>, arr1: Array.<string>, ): boolean

Check if the first input array contains all the elements of the second input array.

Parameters

  • arr0 (Array.<string>) — The test array.
  • arr1 (Array.<string>) — The elements to check in the first array.

Returns

  • boolean — True if all the elements of arr1 are included in arr0.

arraySortEquals(arr0: Array, arr1: Array): boolean

Check for array equality after sorting.

Parameters

  • arr0 (Array) — First array.
  • arr1 (Array) — Second array.

Returns

  • boolean — True if both array are defined and contain same values.

arrayEquals(arr0: Array, arr1: Array): boolean

Check for array equality.

Parameters

  • arr0 (Array) — First array.
  • arr1 (Array) — Second array.

Returns

  • boolean — True if both array are defined and contain same values.

uint8ArrayToString(arr: Uint8Array): string

Convert a Uint8Array to a string.

Parameters

  • arr (Uint8Array) — The array to convert.

Returns

  • string — The array as string.

findInArraySubset( arr: Uint8Array, callbackFn: function, start: number | undefined, end?: number | undefined, ): number | undefined

Array find in a subset of the input array. Equivalent to: arr.slice(start, end).find(callbackFn).

Parameters

  • arr (Uint8Array) — The input array to search.
  • callbackFn (function) — The find function.
  • start (number | undefined) — The array start index.
  • end (number | undefined, optional) — The array end index.

Returns

  • number | undefined — The index where the element was found.

getFindArrayInArrayCallback(arr1: Uint8Array): function

Get a find in array callback.

Parameters

  • arr1 (Uint8Array) — The array to find.

Returns

  • function — The find callback function.

parseMultipart(arr: ArrayBuffer): Array

Extract each element of a multipart ArrayBuffer.

Ref: https://en.wikipedia.org/wiki/MIME#Multipart_messages.

Parameters

  • arr (ArrayBuffer) — The multipart array.

Returns

  • Array — The multipart parts as an array of object as {'Content-Type', ..., data} (depending on header tags).

buildMultipart(parts: Array, boundary: string): Uint8Array

Build a multipart message.

Ref:

Parameters

  • parts (Array) — The message parts as an array of object containing content headers and messages as the data property (as returned by parse).
  • boundary (string) — The message boundary.

Returns

  • Uint8Array — The full multipart message.

isEqualRgb(c1: RGB, c2: RGB): boolean

Check if two rgb objects are equal.

Parameters

  • c1 (RGB) — The first colour.
  • c2 (RGB) — The second colour.

Returns

  • boolean — True if both colour are equal.

ybrToRgb(y: number, cb: number, cr: number): RGB

Convert YBR to RGB.

Ref:

Parameters

  • y (number) — The Y component.
  • cb (number) — The Cb component.
  • cr (number) — The Cr component.

Returns

  • RGB — RGB equivalent as {r,g,b}.

hexToRgb(hexStr: string): RGB

Convert a hex color into RGB.

Parameters

  • hexStr (string) — The hex color as '#ab01ef'.

Returns

  • RGB — The RGB values as {r,g,b}.

rgbToHex(rgb: RGB): string

Convert RGB to its hex equivalent.

Parameters

  • rgb (RGB) — The RGB object as {r,g,b}.

Returns

  • string — A string representing the hex color as '#ab01ef'.

getBrightness(rgb: RGB): number

Get the brightness of a RGB colour: calculates the luma (Y) of the YIQ colour space.

Ref: https://en.wikipedia.org/wiki/YIQ#From_RGB_to_YIQ.

Parameters

  • rgb (RGB) — RGB triplet.

Returns

  • number — The brightness ([0,1]).

isDarkColour(hexColour: string): boolean

Check if a colour given in hexadecimal format is dark.

Parameters

  • hexColour (string) — The colour (as '#ab01ef').

Returns

  • boolean — True if the colour is dark (brightness < 0.5).

getShadowColour(hexColour: string): string

Get the shadow colour of an input colour.

Parameters

  • hexColour (string) — The colour (as '#ab01ef').

Returns

  • string — The shadow colour (white or black).

uintLabToLab(triplet: object): object

Unsigned int CIE LAB value ([0, 65535]) to CIE LAB value (L: [0, 100], a: [-128, 127], b: [-128, 127]).

Parameters

  • triplet (object) — CIE LAB triplet as {l,a,b} with unsigned range.

Returns

  • object — CIE LAB triplet as {l,a,b} with CIE LAB range.

labToUintLab(triplet: object): object

CIE LAB value (L: [0, 100], a: [-128, 127], b: [-128, 127]) to unsigned int CIE LAB ([0, 65535]).

Parameters

  • triplet (object) — CIE XYZ triplet as {l,a,b} with CIE LAB range.

Returns

  • object — CIE LAB triplet as {l,a,b} with unsigned range.

cielabToCiexyz(triplet: object): Scalar3D

Convert CIE LAB to CIE XYZ (standard illuminant D65, 2degree 1931).

Ref: https://en.wikipedia.org/wiki/CIELAB_color_space#From_CIELAB_to_CIEXYZ.

Parameters

  • triplet (object) — CIE LAB triplet as {l,a,b}.

Returns

  • Scalar3D — CIE XYZ triplet as {x,y,z}.

ciexyzToCielab(triplet: Scalar3D): object

Convert CIE XYZ to CIE LAB (standard illuminant D65, 2degree 1931).

Ref: https://en.wikipedia.org/wiki/CIELAB_color_space#From_CIEXYZ_to_CIELAB.

Parameters

  • triplet (Scalar3D) — CIE XYZ triplet as {x,y,z}.

Returns

  • object — CIE LAB triplet as {l,a,b}.

ciexyzToSrgb(triplet: Scalar3D): RGB

Convert CIE XYZ to sRGB.

Ref: https://en.wikipedia.org/wiki/SRGB#From_CIE_XYZ_to_sRGB.

Parameters

  • triplet (Scalar3D) — CIE XYZ triplet as {x,y,z}.

Returns

  • RGB — 'sRGB' triplet as {r,g,b}.

srgbToCiexyz(triplet: RGB): Scalar3D

Convert sRGB to CIE XYZ.

Ref: https://en.wikipedia.org/wiki/SRGB#From_sRGB_to_CIE_XYZ.

Parameters

  • triplet (RGB) — 'sRGB' triplet as {r,g,b}.

Returns

  • Scalar3D — CIE XYZ triplet as {x,y,z}.

cielabToSrgb(triplet: object): RGB

Convert CIE LAB to sRGB (standard illuminant D65).

Parameters

  • triplet (object) — CIE LAB triplet as {l,a,b}.

Returns

  • RGB — 'sRGB' triplet as {r,g,b}.

srgbToCielab(triplet: RGB): object

Convert sRGB to CIE LAB (standard illuminant D65).

Parameters

  • triplet (RGB) — 'sRGB' triplet as {r,g,b}.

Returns

  • object — CIE LAB triplet as {l,a,b}.

colourNameToHex(name: string): string

Get the hex code of a string colour for a colour used in pre dwv v0.17.

Parameters

  • name (string) — The name of a colour.

Returns

  • string — The hex representing the colour.

getDefaultColour(number: number): RGB

Get a default RGB colour for a given number (for example a segment number).

Parameters

  • number (number) — The input number.

Returns

  • RGB — A colour.

mergeObjects( obj1: object, obj2: object, idKey: string, valueKey: string, secondIdGetter?: function, ): object

Merge two similar objects.

Objects need to be in the form of: { idKey: {valueKey: ['0']}, key0: {valueKey: ["abc"]}, key1: {valueKey: [33]} } .

Merged objects will be in the form of: { mergeId: ['0','1','2'], idKey: {valueKey: { 0: ['0'], 1: ['1'], 2: ['2'] }}, key0: {valueKey: { 0: ["abc"], 1: ["def"], 2: ["ghi"] }}, key1: {valueKey: { 0: [33], 1: [44], 2: [55] }} } .

Parameters

  • obj1 (object) — The first object, can be the result of a previous merge.
  • obj2 (object) — The second object.
  • idKey (string) — The key to use as index for duplicate values.
  • valueKey (string) — The key to use to access object values.
  • secondIdGetter (function, optional) — Function (obj) => number|undefined called on each raw (not yet merged) object to get its second id, added as a suffix to its base id to disambiguate objects that would otherwise share the same base id (to differentiate time points for example). Defaults to no second id.

Returns

  • object — The merged object.

capitaliseFirstLetter(string: string): string

Capitalise the first letter of a string.

Parameters

  • string (string) — The string to capitalise the first letter.

Returns

  • string — The new string.

startsWith( str: string, search: string, rawPos?: number, ): boolean

Check if a string starts with the input element.

Parameters

  • str (string) — The input string.
  • search (string) — The searched start.
  • rawPos (number, optional) — The position in this string at which to begin searching for searchString. Defaults to 0.

Returns

  • boolean — True if the input string starts with the searched string.

endsWith(str: string, search: string): boolean

Check if a string ends with the input element.

Parameters

  • str (string) — The input string.
  • search (string) — The searched ending.

Returns

  • boolean — True if the input string ends with the searched string.

splitKeyValueString(inputStr: string): object

Split key/value string: key0=val00&key0=val01&key1=val10 will return {key0 : [val00, val01], key1 : val1}.

Parameters

  • inputStr (string) — The string to split.

Returns

  • object — The split string.

getFlags(inputStr: string): Array.<string>

Get flags from an input string. Flags are words surrounded with curly braces.

Parameters

  • inputStr (string) — The input string.

Returns

  • Array.<string> — An array of found flags.

replaceFlags(inputStr: string, values: object): string

Replace flags in a input string. Flags are keywords surrounded with curly braces.

Parameters

  • inputStr (string) — The input string.
  • values (object) — A object of {value, unit}.

Returns

  • string — The result string.

getRootPath(path: string): string

Get the root of an input path. Splits using / as separator.

Parameters

  • path (string) — The input path.

Returns

  • string — The input path without its last part.

getFileExtension(filePath: string): string | undefined

Get a file extension: anything after the last dot. File name starting with a dot are discarded. Extensions are expected to contain at least one letter.

Parameters

  • filePath (string) — The file path containing the file name.

Returns

  • string | undefined — The lower case file extension or undefined for none.

stringToUint8Array(str: string): Uint8Array

Convert a string to a Uint8Array.

Parameters

  • str (string) — The string to convert.

Returns

  • Uint8Array — The Uint8Array.

getHardwareConcurrency(): number | undefined

Get the number of logical processors.

Returns

  • number | undefined — The number of logical processors (navigator.hardwareConcurrency), undefined if not available.

getDefaultPoolSize(): number

Get the default thread pool size: half the number of logical processors (at least one), or FALLBACK_POOL_SIZE if not available. Leaves room for the main thread and limits the number of workers (and their buffer copies), which matters on memory limited devices such as iOS ones.

Returns

  • number — The pool size.

clampPoolSize(poolSize: number): number

Clamp a thread pool size to the number of logical processors, if available.

Parameters

  • poolSize (number) — The pool size.

Returns

  • number — The clamped pool size.

getUrlFromUri(uri: string): URL

Get an full object URL from a string uri.

Parameters

  • uri (string) — A string representing the url.

Returns

  • URL — A URL object.

splitUri(uri: string): object

Split an input URI: 'root?key0=val00&key0=val01&key1=val10' returns { base : root, query : [ key0 : [val00, val01], key1 : val1 ] } Returns an empty object if the input string is not correct (null, empty...) or if it is not a query string (no question mark).

Parameters

  • uri (string) — The string to split.

Returns

  • object — The split string.

getUriQuery(uri: string): object

Get the query part, split into an array, of an input URI. The URI scheme is: base?query#fragment.

Parameters

  • uri (string) — The input URI.

Returns

  • object — The query part, split into an array, of the input URI.

decodeQuery(query: object, callback: function, options: object)

deprecated
uri.js:84

Generic URI query decoder. Supports manifest: [dwv root]?input=encodeURIComponent('[manifest file]')&type=manifest. Or encoded URI with base and key value/pairs: [dwv root]?input=encodeURIComponent([root]?key0=value0&key1=value1).

Since v0.36, please use specialised getURLsFromKeyValueUri and app.loadURLS or handleURLsFromWeasisXMLManifest.

Parameters

  • query (object) — The query part to the input URI.
  • callback (function) — The function to call with the decoded file urls.
  • options (object) — Optional url request options.

getURLsFromKeyValueUri(uri: string): Array.<string> | undefined

Get a list of URLs from a uri containing key-value pairs as in: [dwv root]?input=encodeURIComponent([root]?key0=value0&key1=value1).

Parameters

  • uri (string) — The input URI.

Returns

  • Array.<string> | undefined — The list of URLs.

handleURLsFromWeasisXMLManifest(uri: string, callback: function)

Handle (ie call callback) with the list of urls contained in a WEASIS XML manifest provided via a uri as in: [dwv root]?input=encodeURIComponent('[manifest file]')&type=manifest.

Parameters

  • uri (string) — The input URI.
  • callback (function) — The function to call with the decoded file urls.

decodeKeyValueUri( uri: string, replaceMode: string, ): Array.<string>

Decode a Key/Value pair URI. If a key is repeated, the result be an array of base + each key.

Parameters

  • uri (string) — The URI to decode.
  • replaceMode (string) — The key replace mode. Can be:

Returns

  • Array.<string> — The list of input file urls.

parseWeasisXMLManifest( manifest: XMLDocument, nslices: number, ): Array.<string>

Parse a WEASIS XML manifest. See: https://weasis.org/en/basics/customize/integration/#build-an-xml-manifest.

Parameters

  • manifest (XMLDocument) — The manifest to decode.
  • nslices (number) — The number of slices to load.

Returns

  • Array.<string> — A list of WADO urls.

getRleFragment(segments: Array.<Array.<number>>): Uint8Array

Create a RLE fragment from already encoded segments: 64 bytes header (number of segments + 15 segment offsets) followed by the segments. Ref: https://dicom.nema.org/medical/dicom/2024a/output/chtml/part05/sect_G.5.html.

Parameters

  • segments (Array.<Array.<number>>) — The encoded segments, as byte values (negative counts can be given as signed values).

Returns

  • Uint8Array — The RLE fragment.

decode(fragment: Uint8Array, meta: object): TypedArray

Decode a fragment.

Parameters

  • fragment (Uint8Array) — The RLE fragment.
  • meta (object) — The meta data: {bitsAllocated, isSigned, sliceSize, samplesPerPixel, planarConfiguration}.

Returns

makeMultiFrameElements( temporalPositionIndex: number, numberOfFrames?: number, ): Record.<string, DataElement>

Create DICOM elements for a multi-frame file whose frames all share the given TemporalPositionIndex.

Parameters

  • temporalPositionIndex (number) — The per-frame temporal position index value.
  • numberOfFrames (number, optional) — Optional number of frames (defaults to 2).

Returns

makeEnhancedMRElements( bValues: Array.<number>, ): Record.<string, DataElement>

Create DICOM elements for an enhanced MR multi-frame file with per-frame diffusion b-values.

Parameters

  • bValues (Array.<number>) — The per-frame b-values.

Returns

makePerFrameElements( frameValues: object, extraElements?: Record.<string, DataElement>, ): Record.<string, DataElement>

Create DICOM elements for a multi-frame file with per-frame TemporalPositionIndex and/or diffusion b-values.

Parameters

  • frameValues (object) — The per-frame values: optional temporalPositions, bValues and dimensionIndexValues arrays.
  • extraElements (Record.<string, DataElement>, optional) — Optional root elements.

Returns

makeDataElement(vr: string, value: Array): DataElement

Create a data element with a given VR and value.

Parameters

  • vr (string) — The value representation.
  • value (Array) — The element value.

Returns

getCandidate(name: string): function

Get a candidate getter by name.

Parameters

  • name (string) — The candidate name.

Returns

  • function — The getter.

b64urlToArrayBuffer(str: string): ArrayBuffer

Convert a base64 url to an ArrayBuffer. Something like: 'data:application/dicom;base64,SGVsbG8sIFdvcmxkIQ==' The function is independent from the mime type.

Parameters

  • str (string) — Base64 url string.

Returns

  • ArrayBuffer — The corresponding buffer.

createDrawLayer(ids: Array.<string>): DrawLayer

Create a draw layer with shape groups.

Parameters

  • ids (Array.<string>) — The shape group ids.

Returns

getOpacity(drawLayer: DrawLayer, id: string): number

Get the opacity of a group.

Parameters

  • drawLayer (DrawLayer) — The draw layer.
  • id (string) — The group id.

Returns

  • number — The group opacity.

createPositionedDrawLayer(circles: Array.<object>): DrawLayer

Create a draw layer at a current position with circle annotations.

Parameters

  • circles (Array.<object>) — The circles as {id, x, y, r}.

Returns

getItem(pos: string, value: string): object

Create an info data item.

Parameters

  • pos (string) — The position.
  • value (string) — The value.

Returns

  • object — The info data item.

createInfoLayer(groupDivId: string): Object

Create an info layer inside a layer group div appended to the document.

Parameters

  • groupDivId (string) — The layer group div id.

Returns

  • Object — The group div and info layer.

makeBinderLayerGroup( dataId: string, position: Array.<number>, size: Array.<number>, geometry?: Geometry, ): Object

Create a layer group mock with one view layer, as used by the position binder.

Parameters

  • dataId (string) — The view layer data id.
  • position (Array.<number>) — The view layer current position.
  • size (Array.<number>) — The view layer image size.
  • geometry (Geometry, optional) — The view layer image geometry.

Returns

  • Object — The layer group and its view controller.

firePositionEvent( binder: PositionBinder, source: object, target: object, event: CustomEvent, )

Fire a position change event from a source layer group to a position binder of a target layer group.

Parameters

  • binder (PositionBinder) — The position binder.
  • source (object) — The source layer group mock.
  • target (object) — The target layer group mock.
  • event (CustomEvent) — The position change event.

makeVolumeGeometry( name: string, values: Array.<number>, ): Geometry

Create a geometry with volume ids.

Parameters

  • name (string) — The volume id name.
  • values (Array.<number>) — The volume id values.

Returns

makePositionEvent( dataid: string, position: Array.<number>, diffDims: Array.<number>, ): CustomEvent

Create a position change event.

Parameters

  • dataid (string) — The source data id.
  • position (Array.<number>) — The source position.
  • diffDims (Array.<number>) — The modified dimensions.

Returns

  • CustomEvent — The event.

getSetPosition(vc: object): Array.<number>

Get the position set on a view controller mock.

Parameters

  • vc (object) — The view controller mock.

Returns

  • Array.<number> — The position values.

makeWindowLevelBinderLayerGroup( dataId: string, presetNames: Array.<string>, ): Object

Create a layer group mock with one view layer, as used by the window/level binder.

Parameters

  • dataId (string) — The view layer data id.
  • presetNames (Array.<string>) — The view controller preset names.

Returns

  • Object — The layer group and its view controller.

makeWindowLevelEvent(dataid: string, value: Array): CustomEvent

Create a window/level change event.

Parameters

  • dataid (string) — The source data id.
  • value (Array) — The event value: [center, width, presetName].

Returns

  • CustomEvent — The event.

makeDiv(id: string): HTMLDivElement

Parameters

  • id (string) — The div id.

Returns

  • HTMLDivElement — A div appended to the document body.

createViewLayer( isMask: boolean, checker?: CanvasSizeChecker, ): ViewLayer

Create a view layer.

Parameters

  • isMask (boolean) — True to create a mask view layer.
  • checker (CanvasSizeChecker, optional) — Optional canvas size checker.

Returns

getOpacity(viewLayer: ViewLayer, segmentNumber: number): number

Get the highlight opacity of a segment.

Parameters

  • viewLayer (ViewLayer) — The view layer.
  • segmentNumber (number) — The segment number.

Returns

  • number — The segment highlight opacity.

makeAnnotation(uid: string): object

Build a minimal annotation-like stub with a given tracking UID. Stubs out setViewController and updateQuantification so the group can delegate to them without importing the full Annotation class.

Parameters

  • uid (string) — The tracking UID.

Returns

  • object — Annotation stub.

lastPool(): object

Return the ThreadPool mock instance created by the last PixelBufferDecoder constructor call.

Returns

  • object — The mock pool instance.

getBuffer( config: object, syntax: string, structure?: object, ): ArrayBuffer

Generate the DICOM buffer of the first file of a data structure.

Parameters

  • config (object) — The data configuration.
  • syntax (string) — The transfer syntax.
  • structure (object, optional) — The data structure, defaults to single slice.

Returns

  • ArrayBuffer — The DICOM buffer.

getReferencePixels( config: object, structure?: object, ): Array.<number>

Get the reference (uncompressed) pixels of the first file of a data structure.

Parameters

  • config (object) — The data configuration.
  • structure (object, optional) — The data structure, defaults to single slice.

Returns

  • Array.<number> — The pixel values.

getRecordingConverter(options?: object): object

Create a converter that records all its events.

Parameters

  • options (object, optional) — Optional converter options.

Returns

  • object — The converter and the recorded events as {converter, events}, each event being {type, event}.

eventsOfType( events: Array.<object>, type: string, ): Array.<object>

Get the events of a given type.

Parameters

  • events (Array.<object>) — The recorded events.
  • type (string) — The event type.

Returns

  • Array.<object> — The events of that type.

getReferenceFrames( elements: object, numberOfFrames: number, ): Array.<Array.<number>>

Get the reference (uncompressed) frames of a file, in encoding order.

Parameters

  • elements (object) — The file data elements.
  • numberOfFrames (number) — The number of frames.

Returns

  • Array.<Array.<number>> — The frames pixel values.

getFramesPerFile(structure: object): number

Get the number of frames per file of a data structure.

Parameters

  • structure (object) — The data structure.

Returns

  • number — The number of frames.

convertDeferred( buffers: Array.<ArrayBuffer>, sortTasks: function, options?: object, setup?: function, ): Array.<object>

Convert buffers with deferred decoding, then run the decoding tasks in the given order (uncompressed data is not deferred).

Parameters

  • buffers (Array.<ArrayBuffer>) — The buffers, one per data index.
  • sortTasks (function) — The pending tasks sort function.
  • options (object, optional) — Optional converter options.
  • setup (function, optional) — Optional converter setup function, called with the recording converter before conversion.

Returns

  • Array.<object> — The recorded events.

getDataControllerSetup(dataController: DataController): function

Get a converter setup function that adds or appends the loaded data to a data controller, as the app does.

Parameters

Returns

  • function — The setup function.

getReferenceImage(config: object, structure: object): object

Build the reference image of a data structure from its uncompressed files, without converter nor data controller: one image per frame appended in encoding order.

Parameters

  • config (object) — The data configuration.
  • structure (object) — The data structure.

Returns

  • object — The reference image.

makeRgbaData(n: number): Uint8ClampedArray

Build a predictable RGBA flat buffer for n pixels. Pixel i has R=i+1, G=i+2, B=i+3, A=255.

Parameters

  • n (number) — Number of pixels.

Returns

  • Uint8ClampedArray — RGBA data.

rgbaToRgb(rgba: Uint8ClampedArray): Uint8Array

Convert RGBA data to the expected RGB buffer (alpha stripped).

Parameters

  • rgba (Uint8ClampedArray) — RGBA pixel data.

Returns

  • Uint8Array — RGB buffer.

makeDomImage(w: number, h: number): object

Make a mock DOM image.

Parameters

  • w (number) — Image width in pixels.
  • h (number) — Image height in pixels.

Returns

  • object — The mock image.

makeImage( width: number, height: number, values: Array.<number>, ): Image

Build a single-slice Image from a flat array of pixel values. The image is width × height × 1, stored as Int16Array.

Parameters

  • width (number) — Number of columns.
  • height (number) — Number of rows.
  • values (Array.<number>) — Pixel values in row-major order (x varies fastest).

Returns

  • Image — The constructed Image.

createFramesImage( factory: ImageFactory, elements: object, numberOfFiles: number, numberOfFrames: number, image?: object, ): object

Create the image of a file frame by frame, the way loaded data is (see DicomBufferToData and DataController): one image per frame, appended to the first one. Single frame data is created at once.

Parameters

  • factory (ImageFactory) — The image factory.
  • elements (object) — The file data elements.
  • numberOfFiles (number) — The number of files.
  • numberOfFrames (number) — The number of frames of the file.
  • image (object, optional) — Optional image to append the frames to.

Returns

  • object — The image.

buildHistogram( counts: Record.<number, number>, rsi?: RescaleSlopeAndIntercept, ): ImageHistogram

Build an image histogram from raw value -> count pairs.

Parameters

  • counts (Record.<number, number>) — Map of raw value to count.
  • rsi (RescaleSlopeAndIntercept, optional) — Optional RSI, defaults to id.

Returns

configToElements(config: object): Record.<string, object>

Parse synthetic SEG config tags into DICOM data elements.

Parameters

  • config (object) — A synthetic-data entry.

Returns

  • Record.<string, object> — DICOM data elements.

buildRefImage(): Image

Build a minimal reference Image matching test-img-00 geometry.

Returns

  • Image — The reference image.

buildMaskImage(configName: string): MaskImage

Build a mask Image matching test-img-00 geometry.

Parameters

  • configName (string) — The config name.

Returns

getSegmentsFromElements( elements: Record.<string, object>, ): Array

Extract the segment array from DICOM data elements.

Parameters

  • elements (Record.<string, object>) — DICOM data elements.

Returns

  • Array — Array of MaskSegment objects.

buildSingleSegmentMask( segNumber: number, label: string, pixelStart: number, pixelCount: number, ): MaskImage

Build a minimal single-segment mask using the test-img-00 geometry.

Parameters

  • segNumber (number) — The segment number.
  • label (string) — The segment label.
  • pixelStart (number) — First pixel index to mark as foreground.
  • pixelCount (number) — Number of contiguous foreground pixels.

Returns

countOf( histogram: ImageHistogram, value: number, ): number | undefined

Get the count of a rescaled value in a histogram.

Parameters

  • histogram (ImageHistogram) — The histogram.
  • value (number) — The rescaled value.

Returns

  • number | undefined — The count, undefined if absent.

makeMockMask(meta?: object): object

Build a minimal mock mask image. Only the methods required by MaskSegmentHelper are present; hasValues and updatePaletteColourMap are Vitest spies so calls can be inspected.

Parameters

  • meta (object, optional) — Optional initial meta object.

Returns

  • object — Mock mask image.

makeRealMask( width: number, height: number, values: Array.<number>, origin?: Point3D, ): Image

Build a real single-component, single-slice Image for findOverlap tests. Uses Uint8Array so segment numbers (0–255) fit without clamping.

Parameters

  • width (number) — Number of columns.
  • height (number) — Number of rows.
  • values (Array.<number>) — Pixel values in row-major order.
  • origin (Point3D, optional) — Optional world-space origin (defaults to 0,0,0).

Returns

  • Image — The constructed image.

makeSeg(number: number, label?: string): MaskSegment

Build a MaskSegment with only number and label set.

Parameters

  • number (number) — Segment number.
  • label (string, optional) — Optional label (defaults to seg-<number>).

Returns

makeGeometry( sizeArr: Array.<number>, spacingArr?: Array.<number>, origin?: Point3D, orientation?: Matrix33, ): Geometry

Build a Geometry.

Parameters

  • sizeArr (Array.<number>) — Size in voxels.
  • spacingArr (Array.<number>, optional) — Spacing per axis (default: all 1).
  • origin (Point3D, optional) — World origin (default: 0,0,0).
  • orientation (Matrix33, optional) — Image orientation (default: identity).

Returns

makeGeometry( sizeArr: Array.<number>, origin?: Point3D, ): Geometry

Build a Geometry with unit spacing and identity orientation.

Parameters

  • sizeArr (Array.<number>) — Size values [nx, ny, nz].
  • origin (Point3D, optional) — World origin (default: 0,0,0).

Returns

  • Geometry — The constructed geometry.

makeHelper( sizeArr: Array.<number>, initIndex: Array.<number>, scrollDim?: number, origin?: Point3D, ): Object

Build a mock view backed by a real Geometry. currentPosition is stored in a shared closure so the helper's position accessor and the geometry stay consistent.

Parameters

  • sizeArr (Array.<number>) — Geometry size values.
  • initIndex (Array.<number>) — Initial position as index values.
  • scrollDim (number, optional, default: 2) — Scroll dimension (default: 2 / z).
  • origin (Point3D, optional) — World origin.

Returns

  • Object — The helper and the underlying geometry.

makeViewHelper( geometry: Geometry, initIndex: Array.<number>, scrollDim?: number, ): PositionHelper

Build a position helper on an existing geometry.

Parameters

  • geometry (Geometry) — The geometry.
  • initIndex (Array.<number>) — Initial position as index values.
  • scrollDim (number, optional, default: 2) — Scroll dimension (default: 2 / z).

Returns

buildRefImage(): Image

Build a minimal reference Image matching test-img-00 geometry: 32×32×1, unit spacing, identity orientation, origin at (0,0,0).

Returns

  • Image — The reference image.

configToElements(config: object): Record.<string, object>

Parse synthetic RTSS config tags into DICOM data elements.

Parameters

  • config (object) — A synthetic-data entry.

Returns

  • Record.<string, object> — DICOM data elements.

makeGeometry( ncols: number, nrows: number, nslices: number, ): Geometry

Build a minimal Geometry: ncols × nrows × nslices, unit spacing.

Parameters

  • ncols (number) — Number of columns.
  • nrows (number) — Number of rows.
  • nslices (number) — Number of slices.

Returns

makePixelBuffer( sliceSize: number, activeOffsets: Array.<number>, ): Uint8Array

Build a pixel buffer for one frame: listed offsets set to 1, rest 0.

Parameters

  • sliceSize (number) — Total pixels per slice (ncols * nrows).
  • activeOffsets (Array.<number>) — Local offsets within the slice to set.

Returns

  • Uint8Array — The pixel buffer.

makeSeg(number: number): MaskSegment

Build a MaskSegment with number and displayValue set.

Parameters

  • number (number) — Segment number.

Returns

makeImageData(size: number): Object

Build a flat RGBA buffer of size pixels, initialised to zero.

Parameters

  • size (number) — Number of pixels.

Returns

  • Object — Minimal ImageData-like object.

makeIterator(values: Array): object

Build a position iterator over an array of pixel values. Each element may be a scalar or an array (e.g. [R, G, B] / [Y, Cb, Cr]).

Parameters

  • values (Array) — Pixel values to iterate.

Returns

  • object — Iterator with a next() method.

makeColourMap(): Object

Build a ColourMap-shaped object with predictable values: red[i] = i, green[i] = 255 - i, blue[i] = (i * 2) % 256.

Returns

  • Object — Colour map.

makeIdentityWindowLut(): Object

Build a minimal WindowLut mock whose getValue returns its input unchanged.

Returns

  • Object — Identity window LUT.

buildHistogram(counts: Record.<number, number>): Histogram

Build a histogram from value -> count pairs.

Parameters

  • counts (Record.<number, number>) — Map of value to count.

Returns

makeDrawDragApp(): object

Returns

makeMinimalDrawLayerForDrag(): object

Draw layer stub: selection misses (non-editable group / no hit).

Returns

  • object — Draw layer mock.

makeDrawPreviewApp(): object

Returns

makeDrawSelectStub(): object

Minimal mock for DrawSelect (methods used by DrawTapBehavior).

Returns

  • object — DrawSelect-like stub.

makeDrawTapApp(): object

Returns

makeMinimalDrawLayer(): object

Returns

  • object — Draw layer mock for tap tests (no hit / non-editable).

createRectangleDrawIntegrationSetup(): object

Konva stage + layer group + app mocks for rectangle finalization tests.

Returns

  • object — Fixture: app, layerGroup, konvaLayer, stage, addedAnnotations, cleanup.

assertRectangleAnnotationOk( annotation: unknown, begin: Point2D, end: Point2D, )

Assert a finalized annotation is a rectangle with expected display corners.

Parameters

makeMockViewController(): object

Create a minimal View Controller mock.

Returns

  • object — The view controller mock.

makeMockViewLayer(viewController?: object): object

Create a minimal View Layer mock.

Parameters

  • viewController (object, optional) — The view controller mock (optional).

Returns

  • object — The view layer mock.

makeMockLayer(): object

Create a minimal Layer mock.

Returns

  • object — The layer mock.

makeMockPositionHelper(): object

Create a minimal Position Helper mock.

Returns

  • object — The position helper mock.

makeMockLayerGroup(viewLayer?: object, layer?: object): object

Create a minimal Layer Group mock.

Parameters

  • viewLayer (object, optional) — The view layer mock (optional).
  • layer (object, optional) — The active layer mock (optional).

Returns

  • object — The layer group mock.

makeMockDataController(): object

Create a minimal DataController mock.

Returns

  • object — The data controller mock.

makeMockApp(): object

Create a minimal App mock.

Returns

  • object — The app mock.

makeMockWheelEvent( deltaY?: number, wheelDeltaY?: number, ): object

Create a minimal Wheel Event mock.

Parameters

  • deltaY (number, optional) — The deltaY value.
  • wheelDeltaY (number, optional) — The wheelDeltaY value.

Returns

  • object — The wheel event mock.

makeDrawApp(overrides?: object): object

Parameters

  • overrides (object, optional) — Override app methods.

Returns

  • object — Minimal App stub for Draw.

makeImage3x3(values: Array.<number>): Image

Small greyscale image for filter runs (3×3 matches convolution kernels).

Parameters

  • values (Array.<number>) — Pixel values row-major.

Returns

makeFilterApp(image: Image): object

Minimal app stub with image data for Threshold, Sharpen, and Sobel.

Parameters

  • image (Image) — Pixel data.

Returns

  • object — App mock.

getResultImageFromSetImage(app: object): Image

Image passed to DataController#setImage from RunFilterCommand#execute.

Parameters

Returns

  • Image — The new image for dataId.

makeFloodfillAppMock(): object

Minimal app stub for Floodfill and LayerGroupPointer.

Returns

  • object — Mock application.

setupLayerCanvas(groupDivId: string): Object

Minimal layer DOM: canvas inside .layer div (see getLayerDetailsFromEvent).

Parameters

  • groupDivId (string, default: "layerGroupPtrTest") — Layer group id (e.g. layerGroup0).

Returns

  • Object — Canvas and id.

mouseEvent( type: string, target: EventTarget, offsetX: number, offsetY: number, ): MouseEvent

Parameters

  • type (string) — The DOM event type.
  • target (EventTarget) — The event target node.
  • offsetX (number) — Horizontal offset on the target.
  • offsetY (number) — Vertical offset on the target.

Returns

  • MouseEvent — Synthetic mouse event for tests.

touchEvent(type: string, target: EventTarget): TouchEvent

Parameters

  • type (string) — Touch event type.
  • target (EventTarget) — Usually the canvas under .layer.

Returns

  • TouchEvent — Synthetic touch event for tests.

wheelEvent(target: EventTarget, opts?: object): WheelEvent

Parameters

  • target (EventTarget) — The event target, usually the canvas under a .layer div.
  • opts (object, optional) — Optional deltaY and wheelDeltaY for tick shaping.

Returns

  • WheelEvent — Synthetic wheel event for tests.

makeLivewireAppMock(): object

Minimal app stub for Livewire and LayerGroupPointer.

Returns

  • object — Mock application.

p(x: number, y: number): Point2D

Parameters

  • x (number) — X.
  • y (number) — Y.

Returns

makeArrowAnnotation(tip?: Point2D, tail?: Point2D): object

Arrow annotation mock: mathShape = tip, referencePoints[0] = tail.

Parameters

Returns

  • object — Annotation-like object.

makeBiDimAnnotation( x0: number, y0: number, x1: number, y1: number, ): object

Build a horizontal BidimensionalLine annotation via the factory. The short axis is fully initialised by setAnnotationMathShape.

Parameters

  • x0 (number) — X of begin point.
  • y0 (number) — Y of begin point.
  • x1 (number) — X of end point.
  • y1 (number) — Y of end point.

Returns

  • object — Annotation mock with mathShape set.

p(x: number, y: number): Point2D

Parameters

  • x (number) — X.
  • y (number) — Y.

Returns

p(x: number, y: number): Point2D

Parameters

  • x (number) — X.
  • y (number) — Y.

Returns

p(x: number, y: number): Point2D

Parameters

  • x (number) — X.
  • y (number) — Y.

Returns

p(x: number, y: number): Point2D

Parameters

  • x (number) — X.
  • y (number) — Y.

Returns

p(x: number, y: number): Point2D

Parameters

  • x (number) — X.
  • y (number) — Y.

Returns

p(x: number, y: number): Point2D

Parameters

  • x (number) — X.
  • y (number) — Y.

Returns

p(x: number, y: number): Point2D

Create a Point2D.

Parameters

  • x (number) — X coordinate.
  • y (number) — Y coordinate.

Returns

makeAnnotation(mathShape?: object): object

Standard annotation mock (mathShape + mocked hooks).

Parameters

  • mathShape (object, optional) — The math shape.

Returns

  • object — The annotation mock.

makeArrowAnnotation(tip?: Point2D, tail?: Point2D): object

Arrow annotation mock: mathShape = tip Point2D, referencePoints[0] = tail.

Parameters

  • tip (Point2D, optional) — The tip point (mathShape).
  • tail (Point2D, optional) — The tail point (referencePoints[0]).

Returns

  • object — The annotation mock.

p(x: number, y: number): Point2D

Create a Point2D.

Parameters

  • x (number) — X coordinate.
  • y (number) — Y coordinate.

Returns

makeAnnotation(mathShape?: object): object

Standard annotation mock.

Parameters

  • mathShape (object, optional) — The math shape.

Returns

  • object — The annotation mock.

makeArrowAnnotation(tip?: Point2D, tail?: Point2D): object

Arrow annotation mock (mathShape = Point2D, referencePoints[0] = Point2D).

Parameters

  • tip (Point2D, optional) — The tip point.
  • tail (Point2D, optional) — The tail point.

Returns

  • object — The annotation mock.

p(x: number, y: number): Point2D

Create a Point2D.

Parameters

  • x (number) — X coordinate.
  • y (number) — Y coordinate.

Returns

makeAnnotation(mathShape?: object): object

Standard annotation mock.

Parameters

  • mathShape (object, optional) — The math shape.

Returns

  • object — The annotation mock.

makeArrowAnnotation(tip?: Point2D, tail?: Point2D): object

Arrow annotation mock (mathShape = Point2D, referencePoints[0] = Point2D).

Parameters

  • tip (Point2D, optional) — The tip point.
  • tail (Point2D, optional) — The tail point.

Returns

  • object — The annotation mock.

makeStyle(): object

Create a minimal Style mock covering all methods used by shape factories and LabelFactory.

Returns

  • object — The style mock.

makeAnnotation(mathShape?: object): object

Create a minimal Annotation-like mock for factory tests.

The returned object has all standard annotation fields; pass any math shape as mathShape. For factories that require extra fields (e.g. ArrowFactory's referencePoints) extend the object at the call site.

Parameters

  • mathShape (object, optional) — The math shape to assign.

Returns

  • object — The annotation mock.

makeShapeGroupWithAnchors( factory: object, ann: object, style: object, ): object

Build a full Konva group for an annotation and attach the factory anchors to it, mirroring the real draw-controller setup so that updateAnnotationOnAnchorMove and updateShapeGroupOnAnchorMove work.

Parameters

  • factory (object) — The shape factory under test.
  • ann (object) — The annotation mock.
  • style (object) — The style mock.

Returns

  • object — The Konva group and anchor list.

makeTask(message?: object, info?: object): WorkerTask

Build a WorkerTask backed by a mock worker so no real Web Worker is spawned. The mock worker exposes postMessage, terminate, onmessage, onerror as plain spies. After addWorkerTask runs, the pool wires its own callbacks onto mockWorker.onmessage / .onerror, so calling those in tests simulates the worker responding.

Parameters

  • message (object, optional) — Start message for the task.
  • info (object, optional) — Info object attached to the task.

Returns

  • WorkerTask — The task with an extra .mockWorker property.

makePool(size: number): Object

Build a ThreadPool with spies on every event handler.

Parameters

  • size (number) — Pool size.

Returns

  • Object — Pool and a map of spy handlers.

Instance Fields

_loaderList: Array | null

Singleton loader list, lazily initialised to break the circular dependency: MultipartLoader → MemoryLoader → loaderList → MultipartLoader. The array is created on the first call to getLoaderList(), at which point all modules have been fully evaluated and every class is defined.

Other

custom

Overridalbe custom object for client defined items.

TagKeys

Related DICOM tag keys.

dataEventNames: Array.<string>

List of data event names.

loadEventNames: Array.<string>

List of load event names.

stageControllerEventNames

Events fired by the StageController (propagated to App).

undoEventNames: Array.<string>

List of undo controller event names.

TagKeys

DICOM code tag keys.

DcmCodes

DICOM codes. List: https://dicom.nema.org/medical/dicom/2024a/output/chtml/part16/chapter_d.html.

SctCodes

SNOMED-CT codes. List: https://browser.ihtsdotools.org.

UcumCodes

UCUM codes. Definition: https://unitsofmeasure.org/ucum. List: https://ucum.nlm.nih.gov/ucum-lhc/demo.html.

QuantificationName2DictItem

Quantification name to dictionary item.

QuantificationUnit2UcumKey

Quantification unit to UCUM key. Associated tags:

TagKeys

Related DICOM tag keys.

DirectoryRecordTypes

DICOM record types.

Ref: https://dicom.nema.org/medical/dicom/2024a/output/chtml/part03/sect_F.3.2.2.html#table_F.3-3.

textEncoder

Text encoder used to get string byte lengths.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

NormalisedManufacturers

Normalised manufacturer names.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Small list of used tag keys.

TextDecoder

The text decoder.

Ref: https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

RelationshipTypes

DICOM relationship types.

Ref: https://dicom.nema.org/medical/dicom/2024a/output/chtml/part03/sect_C.17.3.2.4.html#sect_C.17.3.2.4.

ValueTypes

DICOM value types.

Ref: https://dicom.nema.org/medical/dicom/2024a/output/chtml/part03/sect_C.17.3.2.html#sect_C.17.3.2.1.

ContinuityOfContents

DICOM Continuity Of Contents.

Ref: https://dicom.nema.org/medical/dicom/2024a/output/chtml/part03/sect_C.18.8.html#table_C.18.8-1.

ValueTypeValueTagName

DICOM value type to associated tag name.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

GraphicTypes

DICOM graphic types.

Ref: https://dicom.nema.org/medical/dicom/2024a/output/chtml/part03/sect_C.18.6.html#sect_C.18.6.1.2.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

SOPClassUIDs

Related SOP class UIDs.

defaultPrivateBValueRules: Array.<PrivateBValueRule>

Default private b-value tag rules. Tested in order. Rules are either {manufacturer, key} or {uidPrefix, key}. Can be used to extend custom.privateBValueRules.

defaultVolumeIdCandidates: Array.<VolumeIdCandidate>

Ordered list of candidate volume id getters. Since the tag that actually discriminates volumes is not known until the full data is loaded, guessVolumeIndices tries these in order and keeps the first one that produces a valid, consistent per-volume grouping. It is used for the files of a series (see DicomSliceDataList) and for the frames of a multi-frame file (see getSortedFramesGeometry). Most explicit/reliable discriminators come first, AcquisitionTime (the historical default) comes last. Candidates flagged with preLoad are also used while loading (see getVolumeIdTagValue): they must not vary between the slices of a single volume. Candidates either read an index (an id without unit, for example TemporalPositionIdentifier) or a value (for example EchoTime). The associated value of indices is guessed once all data is loaded (see getVolumeValues), values have none.

volumeValueCandidates: Array.<VolumeIdCandidate>

Ordered list of candidate volume associated value getters, used for volume ids that are indices (without unit, for example TemporalPositionIdentifier) once all data is loaded: the first one that gives each volume a time span, the spans not overlapping and following the volume ids order, is kept (see guessVolumeValues). The associated value of a volume is its smallest value, relative to the one of the first volume for relative candidates. Same shape as volume id candidates (preLoad is not used).

loggedDeprecations: Array.<string>

List of already logged deprecation messages.

WriterRuleActions

Writer rule actions.

writerActions: Record.<string, function()>

Possible writer actions.

TagKeys

Small list of used tag keys.

TextEncoder

The text encoder.

Ref: https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder.

dictionary: Record.<string, Record.<string, Array.<string>>>

DICOM tag dictionary 2024a.

tagGroups: Record.<string, string>

Tag groups: key to name pairs. Copied from gdcm-2.6.1\Source\DataDictionary\GroupName.dic -> removed duplicates (commented).

vr32bitVL: Record.<string, boolean>

List of Value Representation (VR) with 32bit Value Length (VL).

Added locally used 'ox'. See http://dicom.nema.org/medical/dicom/2024a/output/chtml/part05/chapter_7.html#table_7.1-1.

vrCharSetString: Record.<string, boolean>

List of string VR with extended or replaced default character repertoire defined in Specific Character Set (0008,0005).

See https://dicom.nema.org/medical/dicom/2024a/output/chtml/part05/chapter_6.html#sect_6.1.2.2.

vrTypes: Record.<string, string>

VR equivalent javascript types.

See https://dicom.nema.org/medical/dicom/2024a/output/chtml/part05/sect_6.2.html#table_6.2-1.

transferSyntaxes: Record.<string, string>

Transfer syntaxes.

See https://dicom.nema.org/medical/dicom/2024a/output/chtml/part06/chapter_A.html#table_A-1.

transferSyntaxKeywords: Record.<string, string>

Transfer syntaxes indexed by keyword.

SOPClassUIDs: Record.<string, string>

Standard SOP Class UIDs indexed by keyword. Not comprehensive, just ones needed by DWV.

See https://dicom.nema.org/medical/dicom/2024a/output/chtml/part04/sect_B.5.html#table_B.5-1.

binderList

List of binders.

InteractionEventNames

List of interaction event names.

NonPassiveInteractionEventNames

List of the interaction event names whose default can be prevented by tools (see LayerGroupPointer): their listeners are not passive.

annotationGroupEventNames: Array.<string>

List of annotation group event names.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

imageEventNames: Array.<string>

List of image event names.

MAX_CONTOUR_SIZE: number

Maximum contour size in pixels.

TagKeys

Related DICOM tag keys.

MetaTagKeys

Meta tag keys.

framesGeometryCache: WeakMap.<DataElements, (Array.<Geometry>|undefined)>

Frames geometry cache: frames of a multi-frame data share the same data elements, avoid calculating it for each frame.

lut_range_max

Lookup tables for image colour display.

luts: Record.<string, ColourMap>

List of available lookup tables (lut).

TagKeys

Related DICOM tag keys.

MetaTagKeys

Meta tag keys.

RequiredDicomTags

List of DICOM Seg required tags.

ML_PER_MM

MAX_LUT_BITS_STORED: number

Maximum number of bits stored for which a pre-computed LUT is created.

TagKeys

Related DICOM tag keys.

MetaTagKeys

Patient/study/series tags to copy into mask meta.

RTStructRequiredTags: Array.<{name: string, enum: Array}>

Required DICOM tags for RT Structure Set Storage.

viewEventNames: Array.<string>

List of view event names.

defaultWlPresets: Record.<string, Record.<string, WindowLevel>>

List of default window level presets.

VoiLutFunctionNames

FileReader

The file reader.

Ref: https://developer.mozilla.org/en-US/docs/Web/API/FileReader.

XMLHttpRequest

The http request.

Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest.

JSZip

The zip library.

Ref: https://github.com/Stuk/jszip.

Orientation

Default anatomical plane orientations.

BRUSH_MASK_FORWARD_EVENT_TYPES

Event types from BrushMaskPaint forwarded by this behavior.

BrushMode

ERROR_MESSAGES

Error strings and helpers shared by mask painting (BrushMaskPaint, BrushDragBehavior).

OPEN_ENDED_TAP_LIMIT: number

Large tap budget when factory ShapeFactory#getNPoints is undefined.

MagicWand

The magic wand namespace.

Ref: https://github.com/Tamersoul/magic-wand-js.

TAP_TOLERANCE: number

Tap hit tolerance, in display pixels.

MouseEventButtons: Readonly.<{left: 0, middle: 1, right: 2, back: 3, forward: 4}>

MouseEvent#button values (left through fifth / forward).

defaultLabelTexts: Record.<string, Record.<string, string>>

List of default label texts.

DRAW_DEBUG

Draw Debug flag.

MAP: Record.<string, KonvaShapePainter>

Registry mapping annotator names to their Konva rendering entry.

toolList: Record.<string, any>

List of client provided tools to be added to the default ones.

Example

CODE
import {App, AppOptions, ViewConfig, toolList} from '//esm.sh/dwv';
// custom tool
class AlertTool {
  mousedown() {alert('AlertTool mousedown');}
  init() {}
  activate() {}
}
// pass it to dwv tool list
toolList['Alert'] = AlertTool;
// create the dwv app
const app = new App();
// initialise
const viewConfig0 = new ViewConfig('layerGroup0');
const viewConfigs = {'*': [viewConfig0]};
const options = new AppOptions(viewConfigs);
options.tools = {Alert: {}};
app.init(options);
// activate tool
app.addEventListener('load', function () {
  app.setTool('Alert');
});
// load dicom data
app.loadURLs([
  'https://raw.githubusercontent.com/ivmartel/dwv/master/tests/data/bbmri-53323851.dcm'
]);

defaultToolList: Record.<string, any>

Default tool list.

toolOptions: Record.<string, Record.<string, any>>

List of client provided tool options to be added to the default ones.

Example

CODE
import {App, AppOptions, ViewConfig, toolOptions, ROI, Point2D}
  from '//esm.sh/dwv';
// custom factory
class LoveFactory {
  getName() {return 'love';}
  static supports(mathShape) {return mathShape instanceof ROI;}
  getNPoints() {return 1;}
  setAnnotationMathShape(annotation, points) {
    const px = points[0].getX();
    const py = points[0].getY();
    annotation.mathShape = new ROI([
      new Point2D(px+15,py), new Point2D(px+10,py-10),
      new Point2D(px,py), new Point2D(px-10,py-10),
      new Point2D(px-15,py), new Point2D(px,py+20)
    ]);
    annotation.getFactory = function () {return new LoveFactory();}
  }
  createShapeGroup(annotation, style) {
    const roi = annotation.mathShape;
    // konva line
    const arr = [];
    for (let i = 0; i < roi.getLength(); ++i) {
      arr.push(roi.getPoint(i).getX());
      arr.push(roi.getPoint(i).getY());
    }
    const shape = new Konva.Line({
      name: 'shape', points: arr,
      stroke: 'red', strokeWidth: 2,
      closed: true
    });
    // konva group
    const group = new Konva.Group();
    group.name('love-group');
    group.visible(true);
    group.id(annotation.trackingUid);
    group.add(shape);
    return group;
  }
}
// pass it to dwv option list
toolOptions['draw'] = {LoveFactory};
// create the dwv app
const app = new App();
// initialise
const viewConfig0 = new ViewConfig('layerGroup0');
const viewConfigs = {'*': [viewConfig0]};
const options = new AppOptions(viewConfigs);
options.tools = {Draw: {options: ['Love']}};
app.init(options);
// activate tool
app.addEventListener('load', function () {
  app.setTool('Draw');
  app.setToolFeatures({shapeName: 'Love'});
});
// load dicom data
app.loadURLs([
  'https://raw.githubusercontent.com/ivmartel/dwv/master/tests/data/bbmri-53323851.dcm'
]);

defaultToolOptions: Record.<string, Record.<string, any>>

Default tool options.

d65

CIE Standard Illuminant D65, standard 2° observer.

Ref: https://en.wikipedia.org/wiki/Illuminant_D65.

i18n

Namespace for translation function (in a namespace to allow for override from client).

FALLBACK_POOL_SIZE

Fallback default thread pool size, used if the number of logical processors is not available.

Worker

Worker background task.

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Worker.

XMLHttpRequest

Decode a WEASIS XML manifest.

Parameters

  • manifestUri (string) — The manifest uri.
  • nslices (number) — The number of slices.
  • callback (function) — The function to call with the WADO urls.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

TagKeys

Related DICOM tag keys.

Syntax

Tests for the 'image/dicomBufferToData.js' file.

idRsi

Tests for the 'image/imageHistogram.js' file.

IDENTITY

The 3×3 identity matrix (row-major).

CASES

Each entry drives the full per-orientation test suite. All expected values are computed from the image geometry orientation G and the view orientation V.

Terminology: T = getTargetOrientation(G, V) = G.asOneAndZeros() × V L = getLegacyTargetOrientation(G, T) = T, or abs(T) when G matches the canonical coronal orientation (legacy annotation cosines).

To add a new orientation case:

  1. Append a new object to CASES.
  2. Fill in geoValues, viewValues, and all expected fields.

Field key: t_123 T * [1,2,3] target de-orient, offset tinv_123 T⁻¹ * [1,2,3] target re-orient, getTargetOrientedPositiveXYZ t_230 T * [2,3,0] getOffset3DFromPlaneOffset({x:2,y:3}) v_123 V * [1,2,3] image de-orient (getImageOriented*) vinv_123 V⁻¹ * [1,2,3] image re-orient (getImageDeOriented*) plane_y_k0 getPositionFromPlanePoint(Point2D(0,1), 0) (T + geo) world_001 getPlanePointFromPosition(Point([0,0,1])) (geo + V) cosines first two columns of T legacy_cosines first two columns of L.

opaqueAlpha

Alpha function that always returns full opacity.

Returns

  • number