aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorcjd242018-03-29 03:50:47 +0100
committercjd242018-03-29 03:50:47 +0100
commit94acccd371a233cda1743d0d387247f0b9b55986 (patch)
tree79f250a8fdd54d379e635ac0a14595a2bb459066 /src
parentV small commit to add some consolidation to filenames/paths (diff)
downloadmedicine-94acccd371a233cda1743d0d387247f0b9b55986.tar.gz
medicine-94acccd371a233cda1743d0d387247f0b9b55986.zip

Please dont use this commit lol

Diffstat (limited to 'src')
-rw-r--r--src/conversion/czi/czi.ts177
-rw-r--r--src/conversion/czi/pyramidWorker.ts161
-rw-r--r--src/conversion/czi/tileExtraction.ts124
-rw-r--r--src/conversion/types/customPyramidIndex.ts27
-rw-r--r--src/conversion/types/cziBinaryTypings.ts23
-rw-r--r--src/conversion/types/helperCZITypes.ts39
6 files changed, 390 insertions, 161 deletions
diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts
index d69d990..b27cfec 100644
--- a/src/conversion/czi/czi.ts
+++ b/src/conversion/czi/czi.ts
@@ -1,103 +1,23 @@
//imports required to make the conversion
import * as fs from 'fs';
+import * as parsexml from 'xml-parser';
import { logger } from '../../logger';
import * as sharp from 'sharp';
import { SharpInstance } from 'sharp';
-import * as parsexml from 'xml-parser';
+import { CZITile, CZIHeightMap, WholeCZIHierarchy } from '../types/customPyramidIndex';
+import { Dimension, DirectoryEntry, SubBlock, Segment } from '../types/cziBinaryTypings';
+import { SupportedViews, TileBounds } from '../types/helperCZITypes';
+import { isTileRelated, regionToExtract } from './tileExtraction';
//various constants for placing files and defining tiles
-const dirname: string = '/cs/scratch/cjd24/0701-extraction';
-const extractionDirectory: string = `${dirname}/`;
-const outputImageData: string = `${dirname}-processed/`;
-const outputImageDirectory: string = `${dirname}-processed/data/`;
-const tileOverlap: number = 0;
+const baseDirname: string = '/cs/scratch/cjd24/0701-extraction';
+const extractionDirectory: string = `${baseDirname}/`;
+const outputImageData: string = `${baseDirname}-processed/`;
+const outputImageDirectory: string = `${baseDirname}-processed/data/`;
+const tileOverlap: number = 0; // Overlap is only half implemented
const tileSize: number = 1024;
const maxZoom: number = 64;
-//Interfaces used to define the tiles incoming from the CZI extraction
-interface Dimension {
- Dimension: string;
- Start: number;
- Size: number;
-}
-interface DirectoryEntry {
- DimensionCount: number;
- DimensionEntries: Dimension[];
-}
-interface SubBlock {
- DirectoryEntry: DirectoryEntry;
- Data: string;
-}
-interface Segment {
- Id: string;
- UsedSize: number;
- Data: SubBlock;
-}
-
-//Interface used to define the pixel-bounds of a 'section' within the image
-class TileBounds {
- public left!: number;
- public right!: number;
- public top!: number;
- public bottom!: number;
- public constructor(leftBound: number, rightBound: number, topBound: number, bottomBound: number) {
- this.left = leftBound;
- this.right = rightBound;
- this.top = topBound;
- this.bottom = bottomBound;
- }
-}
-
-//Interface used to define the structure of the "supportedViews" section
-//of the protocol specification for scalable images
-interface SupportedViews {
- scalable_image: {
- width: number;
- height: number;
- channels: [
- {
- channel_id: string;
- channel_name: string;
- metadata?: parsexml.Node[];
- }
- ];
- real_width?: {
- value?: number;
- units?: string;
- };
- real_height?: {
- value?: number;
- units?: string;
- };
- metadata?: {};
- }
-}
-
-//The following are interfaces for the Custom object storing Information
-//about the CUSTOM pyramid being created for this image
-interface CZITile {
- x_offset: number;
- y_offset: number;
- width: number;
- height: number;
- file: string;
-}
-interface CZIHeightMap {
- zoom_level: number,
- tile_width_count?: number,
- tile_height_count?: number,
- plane: CZITile[][];
-}
-interface WholeCZIHierarchy {
- c_values: [{
- channel_id: string,
- height_map: CZIHeightMap[];
- }],
- c_value_count: number,
- zoom_level_count: number;
- total_files: number;
-}
-
/*
* Simple function to find the tile bounds version of an original tile in the base image
*/
@@ -146,34 +66,8 @@ const findRelatedTiles: Function = function(activeSegments: Segment[], desired:
throw new Error('There was a Sad Boi error');
}
- // Desired X on left is within current tile
- if (((desired.left >= origCoords.left) &&
- (desired.left < origCoords.right)) ||
-
- // Desired X on right is within the current tile
- ((desired.right > origCoords.left) &&
- (desired.right <= origCoords.right)) ||
-
- // Desired tile X overlaps base tile
- ((desired.left < origCoords.left) &&
- (desired.right > origCoords.right))) {
-
- // Desired Y on top is within current tile
- if (((desired.top >= origCoords.top) &&
- (desired.top < origCoords.bottom)) ||
-
- // Desired Y on right is within the current tile
- ((desired.bottom > origCoords.top) &&
- (desired.bottom <= origCoords.bottom)) ||
-
- // Desired tile Y overlaps whole base tile
- ((desired.top < origCoords.top) &&
- (desired.bottom > origCoords.bottom))) {
-
- //If all of the if statements have passed, then this tile
- //is part of the overlap for the new tile to be created.
- relatedTiles.push(baseTile);
- }
+ if (isTileRelated(origCoords, desired)) {
+ relatedTiles.push(baseTile);
}
}
@@ -269,40 +163,8 @@ const orderSegments: Function = function(segments: Segment[]): Segment[][] {
*/
const findRegionToExtract: Function = function(segment: Segment, desired: TileBounds): TileBounds {
- //get the base tile area and create an object for the chunk to extract
- const baseBounds: TileBounds = getOriginalTileBounds(segment);
- let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1);
-
- // check if the new tile overlaps the leftmost boundary
- if (desired.left <= baseBounds.left) {
- chunkToExtract.left = 0;
- } else {
- chunkToExtract.left = desired.left - baseBounds.left;
- }
-
- // check if the new tile overlaps the rightmost boundary
- if (desired.right >= baseBounds.right) {
- chunkToExtract.right = baseBounds.right - baseBounds.left;
- } else {
- chunkToExtract.right = desired.right - baseBounds.left;
- }
-
- // check if the new tile overlaps the top boundary
- if (desired.top <= baseBounds.top) {
- chunkToExtract.top = 0;
- } else {
- chunkToExtract.top = desired.top - baseBounds.top;
- }
-
- // check if the new tile overlaps the bottom boundary
- if (desired.bottom >= baseBounds.bottom) {
- chunkToExtract.bottom = baseBounds.bottom - baseBounds.top;
- } else {
- chunkToExtract.bottom = desired.bottom - baseBounds.top;
- }
-
//return the slice within the base tile for extraction
- return chunkToExtract;
+ return regionToExtract(getOriginalTileBounds(segment) , desired);
};
/*
@@ -797,7 +659,6 @@ const writeJSONtoFile: Function = function(filePath:string, object:Object): void
*/
const createSupportedViewsObject: Function = function(): void
{
-
//parse the xml
parseExtractedXML(`${extractionDirectory}FILE-META-1.xml`);
@@ -821,6 +682,7 @@ const buildCustomPyramids:Function = async function buildCustomPyramids(): Promi
finalCZIJson.c_values = [] as any;
finalCZIJson.c_value_count = 0;
finalCZIJson.total_files = 0;
+ finalCZIJson.complete = false;
//for all channels in the base image
for (const cval of supportedViews.scalable_image.channels) {
@@ -852,22 +714,15 @@ const buildCustomPyramids:Function = async function buildCustomPyramids(): Promi
//write the final json data to file with most recent changes
writeJSONtoFile(`${outputImageData}layout.json`, finalCZIJson);
}
+ finalCZIJson.complete = true;
}
-
-
-
-
-
-
-
-
let finalCZIJson: WholeCZIHierarchy = {} as any;
/*
* Main function used to call the rest of the relevant code to crunch a CZI extraction.
*/
-function main(){
+const main: Function = function() {
console.log("\n");
console.log(">> Checking/Creating output directories...")
diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts
new file mode 100644
index 0000000..bdbcbfa
--- /dev/null
+++ b/src/conversion/czi/pyramidWorker.ts
@@ -0,0 +1,161 @@
+import { CZITile, CZIHeightMap, WholeCZIHierarchy } from '../types/customPyramidIndex';
+import { TileBounds } from '../types/helperCZITypes';
+import * as sharp from 'sharp';
+import { SharpInstance } from 'sharp';
+import * as fs from 'fs';
+import { isTileRelated, regionToExtract } from './tileExtraction';
+
+const processedDirname: string = '/cs/scratch/cjd24/0701-extraction-processed/';
+const processedImages: string = `${processedDirname}data/`;
+const layout: WholeCZIHierarchy = require(`${processedDirname}layout.json`);
+const TEMP_OUTPUT_THING: string = `${processedDirname}finalisedTiles/`;
+const TEMP_REQUESTED_BOUNDS: TileBounds[] =
+[
+ new TileBounds(0, 5000, 2000, 7000),
+ new TileBounds(1000, 6000, 3000, 8000)
+]
+const TEMP_C_VALUE: number = 0, ZOOM_LEVEL: number = 2, TILE_SIZE: number = 1024, TILE_OVERLAP: number = 0;
+
+
+const findRelatedTiles:Function = function(plane: CZIHeightMap, desired: TileBounds): CZITile[][] {
+
+ let relatedTiles: CZITile[][] = [];
+ for (const planeTileRow of plane.plane) {
+ let tileRow: CZITile[] = [], foundTiles: boolean = false;
+ for (const tile of planeTileRow) {
+
+ if (isTileRelated(new TileBounds(tile.x_offset, tile.x_offset + tile.width, tile.y_offset, tile.y_offset + tile.height), desired)) {
+ tileRow.push(tile);
+ foundTiles = true;
+ }
+ }
+ if (foundTiles) {
+ relatedTiles.push(tileRow);
+ }
+ }
+ return relatedTiles;
+}
+
+const extractAndStitch: Function = async function(segments: CZITile[][], desiredRegion: TileBounds): Promise<SharpInstance> {
+
+ // //create a buffer for the rows part of raw image data
+ // let tileVerticalBuffer: Buffer[] = [];
+ //
+ // //for all ros (y coords) in the image
+ // for (const segRow of segments) {
+ // //create a buffer for this row
+ // let tileRow: Buffer[] = [];
+ // let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1);
+ //
+ // //For all of the columns within this row
+ // for (const segCol of segRow) {
+ // //find out the region of the base tile to be added to the new image
+ // chunkToExtract = findRegionToExtract(segCol, desiredRegion);
+ // //extract this section of image data into a sharp buffer
+ // let data: Promise<Buffer> =
+ // sharp(`${extractionDirectory}${segCol.Data.Data}`)
+ // .extract({
+ // left: chunkToExtract.left,
+ // top: chunkToExtract.top,
+ // width: chunkToExtract.right - chunkToExtract.left,
+ // height: chunkToExtract.bottom - chunkToExtract.top
+ // })
+ // .toBuffer();
+ //
+ // //push this data into the row buffer
+ // tileRow.push(await data);
+ // }
+ //
+ // //prepare variables to squash all of the column data into one, for this row
+ // let imageVerticalSlice: SharpInstance = sharp(tileRow[0]);
+ // let bufferBound = findRegionToExtract(segRow[0], desiredRegion);
+ // //check if the inital chunk needs to be extended to support the other columns
+ // if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) {
+ // imageVerticalSlice = await imageVerticalSlice.background({r: 0, g: 0, b: 0, alpha: 0}).extend(
+ // {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))});
+ // }
+ // //for every column along this row, join it to the previous column data
+ // for (let index = 1; index < segRow.length; index++) {
+ // imageVerticalSlice = await imageVerticalSlice
+ // .overlayWith(tileRow[index],
+ // {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)});
+ // }
+ //
+ // //add this horizontal data buffer to the vertical buffer
+ // tileVerticalBuffer.push(await imageVerticalSlice.toBuffer());
+ // }
+ //
+ // //prepare variables used to combine all rows into one image
+ // let finalImage: SharpInstance = sharp(tileVerticalBuffer[0]);
+ // let bufferBound = findRegionToExtract(segments[0][0], desiredRegion);
+ // //Check if the inital row needs to be extended to support further rows
+ // if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) {
+ // finalImage = await finalImage.background({r: 0, g: 0, b: 0, alpha: 0}).extend(
+ // {top:0, left:0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0});
+ // }
+ // //For all further rows in the image, combine it with the previous rows' data
+ // for (let index = 1; index < segments.length; index++) {
+ // finalImage = finalImage.overlayWith(
+ // tileVerticalBuffer[index],
+ // {top: getDimension(segments[index -1][0], 'Y').Size, left: 0});
+ // }
+ //
+// // return the finalised image.
+ // return finalImage;
+ return;
+};
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+const main: Function = function() {
+ if (!layout.complete) {
+ console.error(`The files under: ${processedDirname} have not been finalised yet, please try again later`);
+ return;
+ }
+
+ if (!fs.existsSync(`${TEMP_OUTPUT_THING}`)) {
+ fs.mkdirSync(`${TEMP_OUTPUT_THING}`);
+ }
+
+ let requestCount: number = 0;
+ for (const bound of TEMP_REQUESTED_BOUNDS) {
+ extractAndStitch(
+ findRelatedTiles(layout.c_values[TEMP_C_VALUE].height_map[ZOOM_LEVEL], bound), bound
+ ).then((x: SharpInstance) => x.toFile(`${TEMP_OUTPUT_THING}request-${requestCount++}`));
+ }
+}
+main();
diff --git a/src/conversion/czi/tileExtraction.ts b/src/conversion/czi/tileExtraction.ts
new file mode 100644
index 0000000..9c87dd9
--- /dev/null
+++ b/src/conversion/czi/tileExtraction.ts
@@ -0,0 +1,124 @@
+import { CZITile } from '../types/customPyramidIndex';
+import { TileBounds } from '../types/helperCZITypes';
+import { SharpInstance } from 'sharp';
+import * as sharp from 'sharp';
+
+export const isTileRelated:Function = function(origCoords: TileBounds, desired: TileBounds): boolean {
+
+ if (((desired.left >= origCoords.left) &&
+ (desired.left < origCoords.right)) ||
+
+ // Desired X on right is within the current tile
+ ((desired.right > origCoords.left) &&
+ (desired.right <= origCoords.right)) ||
+
+ // Desired tile X overlaps base tile
+ ((desired.left < origCoords.left) &&
+ (desired.right > origCoords.right)))
+ {
+
+ // Desired Y on top is within current tile
+ if (((desired.top >= origCoords.top) &&
+ (desired.top < origCoords.bottom)) ||
+
+ // Desired Y on right is within the current tile
+ ((desired.bottom > origCoords.top) &&
+ (desired.bottom <= origCoords.bottom)) ||
+
+ // Desired tile Y overlaps whole base tile
+ ((desired.top < origCoords.top) &&
+ (desired.bottom > origCoords.bottom)))
+ {
+
+ //If all of the if statements have passed, then this tile
+ //is part of the overlap for the new tile to be created.
+ return true;
+ }
+ }
+ return false;
+}
+
+
+/*
+ * Takes a base tile, and the whole bounds of a new tile, and uses this
+ * to calculate the region within the base tile that is overlapping the new tile
+ * to be extracted.
+ */
+export const regionToExtract: Function = function(baseBounds: TileBounds, desired: TileBounds): TileBounds {
+
+ //get the base tile area and create an object for the chunk to extract
+ let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1);
+
+ // check if the new tile overlaps the leftmost boundary
+ if (desired.left <= baseBounds.left) {
+ chunkToExtract.left = 0;
+ } else {
+ chunkToExtract.left = desired.left - baseBounds.left;
+ }
+
+ // check if the new tile overlaps the rightmost boundary
+ if (desired.right >= baseBounds.right) {
+ chunkToExtract.right = baseBounds.right - baseBounds.left;
+ } else {
+ chunkToExtract.right = desired.right - baseBounds.left;
+ }
+
+ // check if the new tile overlaps the top boundary
+ if (desired.top <= baseBounds.top) {
+ chunkToExtract.top = 0;
+ } else {
+ chunkToExtract.top = desired.top - baseBounds.top;
+ }
+
+ // check if the new tile overlaps the bottom boundary
+ if (desired.bottom >= baseBounds.bottom) {
+ chunkToExtract.bottom = baseBounds.bottom - baseBounds.top;
+ } else {
+ chunkToExtract.bottom = desired.bottom - baseBounds.top;
+ }
+
+ if (chunkToExtract.left < 0 || chunkToExtract.right < 0 || chunkToExtract.top < 0 || chunkToExtract.bottom < 0) {
+ throw new Error("Chunk to extract from base tile has invalid bound (< 0).");
+ }
+
+ //return the slice within the base tile for extraction
+ return chunkToExtract;
+};
+
+
+// export const createHorizontalImageSlice: Function = async function (bufferBound: TileBounds, tileSize: number, tileOverlap: number, rowLength:number, row: Buffer[]): Promise<Buffer> {
+// //prepare variables to squash all of the column data into one, for this row
+// let imageVerticalSlice: SharpInstance = sharp(row[0]);
+// //check if the inital chunk needs to be extended to support the other columns
+// if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) {
+// imageVerticalSlice = await imageVerticalSlice.background({r: 0, g: 0, b: 0, alpha: 0}).extend(
+// {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))});
+// }
+// //for every column along this row, join it to the previous column data
+// for (let index = 1; index < rowLength; index++) {
+// imageVerticalSlice = await imageVerticalSlice
+// .overlayWith(row[index],
+// {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)});
+// }
+// return imageVerticalSlice.toBuffer();
+// }
+//
+//
+// export const createImageFromHorizontalSlices: Function = async function(bufferBound: TileBounds, horizontalSlices: Buffer[], tileSize: number, tileOverlap: number, rowCount: number, tiles: CZITile[][]): Promise<SharpInstance> {
+// //prepare variables used to combine all rows into one image
+// let finalImage: SharpInstance = sharp(horizontalSlices[0]);
+//
+// //Check if the inital row needs to be extended to support further rows
+// if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) {
+// finalImage = await finalImage.background({r: 0, g: 0, b: 0, alpha: 0}).extend(
+// {top:0, left:0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0});
+// }
+// //For all further rows in the image, combine it with the previous rows' data
+// for (let index = 1; index < rowCount; index++) {
+// finalImage = finalImage.overlayWith(
+// horizontalSlices[index],
+// {top: tiles[index - 1][0].height, left: 0});
+// }
+//
+// return finalImage;
+// }
diff --git a/src/conversion/types/customPyramidIndex.ts b/src/conversion/types/customPyramidIndex.ts
new file mode 100644
index 0000000..f362372
--- /dev/null
+++ b/src/conversion/types/customPyramidIndex.ts
@@ -0,0 +1,27 @@
+//The following are interfaces for the Custom object storing Information
+//about the CUSTOM pyramid being created for this image
+ export interface CZITile {
+ x_offset: number;
+ y_offset: number;
+ width: number;
+ height: number;
+ file: string;
+ }
+
+ export interface CZIHeightMap {
+ zoom_level: number,
+ tile_width_count?: number,
+ tile_height_count?: number,
+ plane: CZITile[][];
+ }
+
+ export interface WholeCZIHierarchy {
+ c_values: [{
+ channel_id: string,
+ height_map: CZIHeightMap[];
+ }],
+ c_value_count: number,
+ zoom_level_count: number;
+ total_files: number;
+ complete: boolean;
+ }
diff --git a/src/conversion/types/cziBinaryTypings.ts b/src/conversion/types/cziBinaryTypings.ts
new file mode 100644
index 0000000..a78b4e9
--- /dev/null
+++ b/src/conversion/types/cziBinaryTypings.ts
@@ -0,0 +1,23 @@
+//Interfaces used to define the tiles incoming from the CZI extraction
+
+export interface Dimension {
+ Dimension: string;
+ Start: number;
+ Size: number;
+}
+
+export interface DirectoryEntry {
+ DimensionCount: number;
+ DimensionEntries: Dimension[];
+}
+
+export interface SubBlock {
+ DirectoryEntry: DirectoryEntry;
+ Data: string;
+}
+
+export interface Segment {
+ Id: string;
+ UsedSize: number;
+ Data: SubBlock;
+}
diff --git a/src/conversion/types/helperCZITypes.ts b/src/conversion/types/helperCZITypes.ts
new file mode 100644
index 0000000..2d57b15
--- /dev/null
+++ b/src/conversion/types/helperCZITypes.ts
@@ -0,0 +1,39 @@
+//Interface used to define the structure of the "supportedViews" section
+//of the protocol specification for scalable images
+import { Node } from 'xml-parser';
+export interface SupportedViews {
+ scalable_image: {
+ width: number;
+ height: number;
+ channels: [
+ {
+ channel_id: string;
+ channel_name: string;
+ metadata?: Node[];
+ }
+ ];
+ real_width?: {
+ value?: number;
+ units?: string;
+ };
+ real_height?: {
+ value?: number;
+ units?: string;
+ };
+ metadata?: {};
+ }
+}
+
+//Interface used to define the pixel-bounds of a 'section' within the image
+export class TileBounds {
+ public left: number;
+ public right: number;
+ public top: number;
+ public bottom: number;
+ public constructor(leftBound: number, rightBound: number, topBound: number, bottomBound: number) {
+ this.left = leftBound;
+ this.right = rightBound;
+ this.top = topBound;
+ this.bottom = bottomBound;
+ }
+}