Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(image loaders): Allow reusing DICOM image loader code for custom image loaders #1509

Merged
merged 6 commits into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions packages/core/examples/dicomLoader/customImageLoader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import type { Types } from '@cornerstonejs/core';
//import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader';
import cornerstoneDICOMImageLoader from '../../../dicomImageLoader/src';
import dicomParser from 'dicom-parser';
import type { AddLogFn } from './logArea';
import { addToCache, dropFromCache, getFromCache } from './metadata';

function _loadImageIntoBuffer(
imageId: string,
options:
| {
targetBuffer?: {
arrayBuffer: ArrayBuffer;
offset: number;
length: number;
};
}
| undefined,
logFn: AddLogFn,
instanceToBytes: (instanceId: string) => Promise<ArrayBuffer>
): Types.IImageLoadObject {
const sopInstanceUid = imageId.replace('custom:', '');
logFn('Loader: starting to load image: ', sopInstanceUid);

const promise = async () => {
try {
const buffer = await instanceToBytes(sopInstanceUid);
const dataSet = dicomParser.parseDicom(new Uint8Array(buffer));
// Add the dataSet to the cache immediately, since createImage()
// already reads metadata.
addToCache(imageId, dataSet);
const pixelData =
cornerstoneDICOMImageLoader.wadouri.getPixelData(dataSet);
const transferSyntax = dataSet.string('x00020010') ?? '';
const image = await cornerstoneDICOMImageLoader.createImage(
imageId,
pixelData,
transferSyntax,
options as any
);

logFn('Loader: done loading image: ', sopInstanceUid);

if (
!options?.targetBuffer ||
!options.targetBuffer.length ||
!options.targetBuffer.offset
) {
return image;
}

(image as any).getPixelData(options.targetBuffer);
return true;
} catch (e) {
logFn('Loader: failed to load image ID', imageId, e);
return false;
}
};

return {
promise: promise() as Promise<Types.IImage>,
cancelFn: () => {
logFn('Loader: cancelling loading image: ', sopInstanceUid);
dropFromCache(imageId);
},
decache: () => {
logFn('Loader: decaching loaded image: ', sopInstanceUid);
dropFromCache(imageId);
},
};
}

function createCustomImageLoader(
logFn: AddLogFn,
instanceToBytes: (instanceId: string) => Promise<ArrayBuffer>
) {
return {
imageLoadFunction: (imageId: string, options: never) => {
return _loadImageIntoBuffer(imageId, options, logFn, instanceToBytes);
},
metadataProvider: (type: string, imageId: string) => {
if (!imageId.startsWith('custom:')) {
return;
}

const sopInstanceUid = imageId.replace('custom:', '');
logFn('Loader: metadata request: ', type, sopInstanceUid);

const dataset = getFromCache(imageId);
if (dataset) {
return cornerstoneDICOMImageLoader.wadouri.metaData.metadataForDataset(
type,
imageId,
dataset
);
}
},
};
}

export default createCustomImageLoader;
127 changes: 127 additions & 0 deletions packages/core/examples/dicomLoader/imageDropArea.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/**
* The Image Drop Area represents any source of images not native to
* Cornerstone or its existing image loaders. For example, your image source
* may be a proprierary URL format, offline local storage or Websockets.
*
* For this file to achieve its intended goal, it should *not* import any
* Cornerstone code, but it may import the dicomParser.
*/

import dicomParser from 'dicom-parser';
import type { AddLogFn } from './logArea';

const SOP_INSTANCE_UID_TAG = 'x00080018';
const SERIES_INSTANCE_UID_TAG = 'x0020000e';

function createImageDropArea(logFn: AddLogFn) {
const area = document.createElement('div');
area.id = 'image-drop-area';
area.style.width = '500px';
area.style.height = '300px';
area.style.background = 'lightblue';
area.style.margin = '5px';
area.style.padding = '5px';

const p = document.createElement('p');
p.appendChild(
document.createTextNode(
'Drop instances or series here to load them. Click on a series name to render it in Cornerstone.'
)
);
area.appendChild(p);

const seriesDiv = document.createElement('div');
area.appendChild(seriesDiv);

const bytes: Record<string, ArrayBuffer> = {};
const series: Record<string, string[]> = {};

// This particular getInstanceBytes doesn't have to be async, but often, it will be.
const getInstanceBytes = (sopInstanceUid: string): Promise<ArrayBuffer> => {
if (sopInstanceUid in bytes) {
return Promise.resolve(bytes[sopInstanceUid]);
} else {
return Promise.reject('SOP instance UID not present in image drop area');
}
};

let emit = (sopInstanceUids: string[]) => {};
const setEmit = (newEmit: typeof emit) => {
emit = newEmit;
};

const redisplay = () => {
seriesDiv.replaceChildren();
Object.entries(series).forEach(([series, instances]) => {
const div = document.createElement('div');
div.appendChild(
document.createTextNode(`${series}: ${instances.length} instances.`)
);
div.style.cursor = 'pointer';
div.addEventListener('click', () => {
emit(instances);
});
seriesDiv.append(div);
});
};

area.ondragover = (event) => event.preventDefault();
area.addEventListener('drop', async (event) => {
event.preventDefault();

const files: File[] = [];
if (event.dataTransfer?.items?.length) {
for (let i = 0; i < event.dataTransfer.items.length; ++i) {
const item = event.dataTransfer.items[i];
if (item.kind === 'file') {
files.push(item.getAsFile()!);
}
}
} else {
for (let i = 0; i < (event.dataTransfer?.files?.length ?? 0); ++i) {
files.push(event.dataTransfer!.files[i]);
}
}

for (let i = 0; i < files.length; ++i) {
try {
const buffer = await files[i].arrayBuffer();
const dataset = dicomParser.parseDicom(new Uint8Array(buffer));

const sopInstanceUid = dataset.string(SOP_INSTANCE_UID_TAG);
if (!sopInstanceUid) {
throw new Error('DICOM instance must have a SOP instance UID');
}
if (sopInstanceUid in bytes) {
// Prevent the SOP instance UID from being added to the series twice
logFn('ignoring duplicate drop of SOP instance UID ', sopInstanceUid);
continue;
}
bytes[sopInstanceUid] = buffer;

let seriesInstanceUid = dataset.string(SERIES_INSTANCE_UID_TAG);
// This is a bit of a hack: if the dataset has no series UID, use the
// sop instance UID as a series UID.
if (!seriesInstanceUid) {
seriesInstanceUid = sopInstanceUid;
}
if (!(seriesInstanceUid in series)) {
series[seriesInstanceUid] = [];
}
series[seriesInstanceUid].push(sopInstanceUid);

redisplay();
} catch (e) {
logFn('Failed to parse DICOM: ', e);
}
}
});

return {
area,
getInstanceBytes,
setEmit,
};
}

export default createImageDropArea;
Loading