Skip to content

Commit

Permalink
Merge pull request #28 from cornerstonejs/fix-float-nan-values
Browse files Browse the repository at this point in the history
fix: invalid float values(IEEE-754) to be valid js values
  • Loading branch information
ladeirarodolfo authored Dec 18, 2020
2 parents 42fbdc9 + fc1fe88 commit d6b92cb
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/nifti/parseNiftiFile.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { external } from '../externalModules.js';
import decodeNiFTIBigEndian from '../shared/niftiBigEndianDecoder.js';
import normalizeInvalid from '../shared/normalizeInvalid.js';

export function parseNiftiHeader (fileData) {
const nifti = external.niftiReader;
Expand Down Expand Up @@ -65,7 +66,7 @@ export function parseNiftiFile (fileData, metaData) {
const arraybuffer = nifti.readImage(metaData.header, fileData);

// reads the image data using nifti-reader-js and puts it in a typed array
let imageData = new TypedArrayConstructor(arraybuffer);
let imageData = normalizeInvalid(metaData.header.datatypeCode, new TypedArrayConstructor(arraybuffer));

if (!metaData.header.littleEndian) {
imageData = decodeNiFTIBigEndian(metaData.header.datatypeCode, imageData);
Expand Down
43 changes: 43 additions & 0 deletions src/shared/normalizeInvalid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { external } from '../externalModules.js';

const nifti = external.niftiReader;

/**
* It will normalize NaN or (-)Infinity values to +MAX_VALUE, -MAX_VALUE or 0.
* It mutates given param
*
* @param {TypedArray} imageData
* @return {TypedArray} Modified imageData
*/
const normalizeInvalidFloat = (imageData) => {
for (let it = 0; it < imageData.length; it++) {
if (isNaN(imageData[it])) {
// defaults to 0
imageData[it] = 0;
} else if (!isFinite(imageData[it])) {
// using the maximum/minimum value instead of infinity
imageData[it] = Math.sign(imageData[it]) * Number.MAX_VALUE;
}
}

return imageData;
};

/**
* Normalize invalid data. Applied to float data only
* It mutates given imageData
* @param {string} datatypeCode
* @param {TypedArray} imageData
* @return {TypedArray} normalized imageData
*/
export default function normalizeInvalid (datatypeCode, imageData) {

switch (datatypeCode) {
case nifti.NIFTI1.TYPE_FLOAT32:
case nifti.NIFTI1.TYPE_FLOAT64:
return normalizeInvalidFloat(imageData);
}

// return not normalized data
return imageData;
}

0 comments on commit d6b92cb

Please sign in to comment.