aboutsummaryrefslogtreecommitdiff
path: root/src/conversion/czi
diff options
context:
space:
mode:
Diffstat (limited to 'src/conversion/czi')
-rw-r--r--src/conversion/czi/convertJxrs.py47
-rw-r--r--src/conversion/czi/czi.ts987
-rwxr-xr-xsrc/conversion/czi/cziConvert.sh7
-rw-r--r--src/conversion/czi/cziconvert.c14
-rw-r--r--src/conversion/czi/pyramidWorker.ts76
-rw-r--r--src/conversion/czi/tileDims.pngbin0 -> 292647 bytes
-rw-r--r--src/conversion/czi/tileExtraction.ts122
7 files changed, 956 insertions, 297 deletions
diff --git a/src/conversion/czi/convertJxrs.py b/src/conversion/czi/convertJxrs.py
index d19a59a..f4b897f 100644
--- a/src/conversion/czi/convertJxrs.py
+++ b/src/conversion/czi/convertJxrs.py
@@ -8,14 +8,21 @@ coutner = 0
def convertjxrs(filename):
- global counter
- global totalFiles
- asTif = filename.rsplit('.',1)[0] + ".tif"
- check_call(['./JxrDecApp', "-i", filename, "-o", asTif])
- check_call(['convert', asTif, filename.rsplit('.',1)[0] + ".png"])
- check_call(['rm', filename, asTif])
- counter += 1
- print (f"> Processed File: {counter}/{totalFiles} : {filename} --> {filename.rsplit('.',1)[0]}.png")
+ global counter
+ global totalFiles
+ try:
+ asTif = filename.rsplit('.',1)[0] + ".tif"
+ check_call(['JxrDecApp', "-i", filename, "-o", asTif])
+ check_call(['convert', asTif, filename.rsplit('.',1)[0] + ".png"])
+ check_call(['rm', filename, asTif])
+ counter += 1
+ except Exception as help:
+ print ("Processing Failed. Probably couldn't find decoder due to invalid system environment path, check this before debugging.");
+ print ("Actual error was:");
+ print (help);
+ exit(0);
+
+ print (f"> Processed File: {counter}/{totalFiles} : {filename} --> {filename.rsplit('.',1)[0]}.png")
if __name__ == "__main__":
@@ -24,15 +31,15 @@ if __name__ == "__main__":
print("\nMissing Argument!\n\nUsage:\npython3 convertJxrs.py <DirectoryContainingJxrs>")
exit(0)
else:
- print("=========== BEGIN JXR CONVERSION ===========")
- print ('Files Dir: ' + argv[1] + '\n')
-
- filenames = glob(argv[1] + 'data-*.jxr')
- counter = 0
- totalFiles = len(filenames)
-
- pool = ThreadPoolExecutor(5)
- for f in pool.map(convertjxrs, filenames):
- pass
- pool.shutdown(True)
- print("=========== FINISH JXR CONVERSION ===========")
+ print("=========== BEGIN JXR CONVERSION ===========")
+ print ('Files Dir: ' + argv[1] + '\n')
+
+ filenames = glob(argv[1] + 'data-*.jxr')
+ counter = 0
+ totalFiles = len(filenames)
+
+ pool = ThreadPoolExecutor(5)
+ for f in pool.map(convertjxrs, filenames):
+ pass
+ pool.shutdown(True)
+ print("=========== FINISH JXR CONVERSION ===========")
diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts
index 127fce6..429f60d 100644
--- a/src/conversion/czi/czi.ts
+++ b/src/conversion/czi/czi.ts
@@ -1,95 +1,56 @@
-
+import { CZIHeightMap, CZITile,
+ WholeCZIHierarchy } from '../types/customPyramidIndex';
+import { Dimension, Segment } from '../types/cziBinaryTypings';
import * as fs from 'fs';
-import { logger } from '../../logger';
+import { SupportedViews, TileBounds, checkForOutputDirectories, writeJSONToFile, execpaths } from '../types/helpers';
+// import { logger } from '../../logger';
import * as sharp from 'sharp';
+// tslint:disable-next-line:no-duplicate-imports
import { SharpInstance } from 'sharp';
+import { isTileRelated, regionToExtract } from './tileExtraction';
import * as parsexml from 'xml-parser';
-
-const extractionDirectory: string = '/cs/scratch/cjd24/0701-extraction/';
-const outputImageDirectory: string = '/cs/scratch/cjd24/0701-extraction-processed2/';
-const tileOverlap: number = 0;
+import { uuid } from '../../uuid'
+
+const readFile = require('util').promisify(fs.readFile);
+const readdir = require('util').promisify(fs.readdir);
+const exists = require('util').promisify(fs.exists);
+
+// Various constants for placing files and defining tiles
+const testFile: string = '/cs/scratch/cjd24/0701.czi'
+let extractDirectory: string = "";
+let outputImageData: string = "";
+let outputImageDirectory: string = "";
+const tileOverlap: number = 0; // Overlap is only half implemented
const tileSize: number = 1024;
const maxZoom: number = 64;
-
-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;
-}
-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 SupportedViews {
- scalable_image: {
- width: number;
- height: number;
- channels: [
- {
- channel_id: string;
- channel_name: string;
- metadata?: {};
- }
- ];
- real_width?: {
- value: number;
- units: string;
- };
- real_height?: {
- value: number;
- units: string;
- };
- metadata?: {};
- };
-}
-interface CZITile {
- x_offset: number;
- y_offset: number;
- width: number;
- height: number;
- file: string;
-}
-interface CZIHeightMap {
- zoom_level: number;
- plane: CZITile[][];
-}
-interface WholeCZIHierarchy {
- c_values: [{
- channel_id: string,
- height_map: CZIHeightMap[];
- }];
-}
-
-const getOriginalTileBounds: Function = function(originalTile: Segment): (TileBounds | null) {
+const shell = require('shelljs');
+const finalCZIJson: WholeCZIHierarchy = {
+ c_value_count: 0,
+ total_files: 0,
+ complete: false,
+ c_values: [],
+ zoom_level_count: 0
+};
+let dataBlocks: Segment[] = [];
+
+/**
+ * Simple function to find the tile bounds version of an original tile
+ * in the base image
+ */
+const getOriginalTileBounds: (originalTile: Segment) => TileBounds = (
+ originalTile: Segment
+): TileBounds => {
const bounds: TileBounds = new TileBounds(-1, -1, -1, -1);
+ // Loop over all dimensions to get the x and y
for (const dimension of originalTile.Data.DirectoryEntry.DimensionEntries) {
switch (dimension.Dimension) {
+ // If we have found x, then match the start and width
case 'X':
bounds.left = dimension.Start;
bounds.right = bounds.left + dimension.Size;
continue;
+ // If we have found y, then match the top and bottom
case 'Y':
bounds.top = dimension.Start;
bounds.bottom = bounds.top + dimension.Size;
@@ -99,87 +60,92 @@ const getOriginalTileBounds: Function = function(originalTile: Segment): (TileBo
}
}
- if (bounds.left < 0 || bounds.right < 0 || bounds.top < 0 || bounds.bottom < 0) {
- return null;
+ // If one of the bounds was not created, then there must have been an error
+ if (bounds.left < 0
+ || bounds.right < 0
+ || bounds.top < 0
+ || bounds.bottom < 0
+ ) {
+ throw new Error(
+ `One of the bounds had a dimension less than zero: ${originalTile.Data.Data}`
+ );
}
-
+ // Successful return
return bounds;
};
-const findRelatedTiles: Function = function(activeSegments: Segment[], desired: TileBounds): Segment[] {
+/**
+ * Function used to find which of the original base tiles are
+ * overlapping with the area of the to-be-created tile
+ */
+const findRelatedTiles: (activeSegments: Segment[], desired: TileBounds) =>
+ Segment[] = (
+ activeSegments: Segment[], desired: TileBounds
+): Segment[] => {
const relatedTiles: Segment[] = [];
+ // For all tiles within the region being checked
for (const baseTile of activeSegments) {
-
- let origCoords: TileBounds | null;
-
- if ((origCoords = getOriginalTileBounds(baseTile)) === null) {
- 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))) {
-
- relatedTiles.push(baseTile);
- }
+ if (isTileRelated(getOriginalTileBounds(baseTile), desired)) {
+ relatedTiles.push(baseTile);
}
}
return relatedTiles;
};
-const getDimension: Function = function(segment: Segment, name: string): Dimension {
+/**
+ * This gets the particular dimension from a segment given a segment
+ * and dimension ID
+ */
+const getDimension: (segment: Segment, name: string) => Dimension = (
+ segment: Segment, name: string
+): Dimension => {
for (const dimension of segment.Data.DirectoryEntry.DimensionEntries) {
+ // If the current dimension is the one we are looking for then return it.
if (dimension.Dimension === name) {
return dimension;
}
}
- throw new Error('Dimension: ' + name + " doesn't exist for segment: " + segment);
+ // If we have gotten to here, then the dimension doesnt exist, so throw error.
+ throw new Error(`Dimension: ${name} doesn't exist for segment: ${segment}`);
};
-const orderSegments: Function = function(segments: Segment[]): Segment[][] {
-
+/**
+ * This takes a selection of segments and ensures that they are ordered
+ * left to right, and top to bottom like the words in a book, so that the
+ * stiching process will take the correct slice from them all.
+ * (this is based on the pixel x-y coords of the segment.)
+ */
+const orderSegments: (segments: Segment[]) => Segment[][] = (
+ segments: Segment[]
+): Segment[][] => {
const output: Segment[][] = [];
+ // So long as there is at least 2 segments to order
if (segments.length > 1) {
let xCoords: number[] = [];
let yCoords: number[] = [];
// Get all x/y's;
+ // However also ensure that all of the segments to be ordered, all come
+ // From the same value of 'C' dimension, otherwise there could be overlaps.
const initC: number = getDimension(segments[0], 'C').Start;
for (const seg of segments) {
if (getDimension(seg, 'C').Start !== initC) {
- throw new Error('Segment array contains multiple values of C - this overlay is currently unsupported within this method');
+ throw new Error(`Segment array contains multiple values of C -\
+ this overlay is currently unsupported within this method`);
}
xCoords.push(getDimension(seg, 'X').Start);
yCoords.push(getDimension(seg, 'Y').Start);
}
- // Filter to get Uniaue Values
- xCoords = xCoords.filter(
- (item: number, index: number, array: number[]) => array.indexOf(item) === index);
- yCoords = yCoords.filter(
- (item: number, index: number, array: number[]) => array.indexOf(item) === index);
+
+ // Filter to get Unique Values
+ const filter: (item: number, index: number, array: number[]) => boolean = (
+ item: number, index: number, array: number[]
+ ): boolean => array.indexOf(item) === index;
+ xCoords = xCoords.filter(filter);
+ yCoords = yCoords.filter(filter);
// Use the filtered list to order the segments into rows
for (const yVal of yCoords) {
@@ -209,54 +175,52 @@ const orderSegments: Function = function(segments: Segment[]): Segment[][] {
// Return the result
return output;
- } else {
- output.push(segments);
- return output;
- }
-};
-
-const findRegionToExtract: Function = function(segment: Segment, desired: TileBounds): TileBounds {
- const baseBounds: TileBounds = getOriginalTileBounds(segment);
- const chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1);
-
- if (desired.left <= baseBounds.left) {
- chunkToExtract.left = 0;
- } else {
- chunkToExtract.left = desired.left - baseBounds.left;
- }
-
- if (desired.right >= baseBounds.right) {
- chunkToExtract.right = baseBounds.right - baseBounds.left;
- } else {
- chunkToExtract.right = desired.right - baseBounds.left;
- }
-
- if (desired.top <= baseBounds.top) {
- chunkToExtract.top = 0;
- } else {
- chunkToExtract.top = desired.top - baseBounds.top;
- }
-
- if (desired.bottom >= baseBounds.bottom) {
- chunkToExtract.bottom = baseBounds.bottom - baseBounds.top;
- } else {
- chunkToExtract.bottom = desired.bottom - baseBounds.top;
}
- return chunkToExtract;
+ // There is only one segment, so no need to re-order.
+ return [segments];
};
-const extractAndStitchChunks: Function = async function(segments: Segment[][], desiredRegion: TileBounds): Promise<SharpInstance> {
+/**
+ * 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.
+ */
+const findRegionToExtract: (
+ segmanet: Segment, desired: TileBounds
+) => TileBounds = (
+ segment: Segment, desired: TileBounds
+): TileBounds => {
+ // Return the slice within the base tile for extraction
+ return regionToExtract(getOriginalTileBounds(segment), desired, 1);
+};
+/*
+ * Take an ordered selection of segments and cookie cutter out a tile from this
+ * into a new image
+ */
+ const extractAndStitchChunks: (
+ segments: Segment[][], desiredRegion: TileBounds
+ ) => Promise<SharpInstance> = async(
+ segments: Segment[][], desiredRegion: TileBounds
+ ): Promise<SharpInstance> => {
+
+ // Create a buffer for the rows part of raw image data
const tileVerticalBuffer: Buffer[] = [];
+ // For all ros (y coords) in the image
for (const segRow of segments) {
+ // Create a buffer for this row
const 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);
- const data: Promise<Buffer> =
- sharp(`${extractionDirectory}${segCol.Data.Data}`)
+ // Extract this section of image data into a sharp buffer
+ let data: Promise<Buffer> =
+ sharp(`${extractDirectory}${segCol.Data.Data}`)
.extract({
left: chunkToExtract.left,
top: chunkToExtract.top,
@@ -265,162 +229,659 @@ const extractAndStitchChunks: Function = async function(segments: Segment[][], d
})
.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]);
- const bufferBound = findRegionToExtract(segRow[0], desiredRegion);
+ const bufferBound: TileBounds = 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.extend(
- {top: 0, left: 0, bottom: 0, right: (tileSize - (bufferBound.right - bufferBound.left))});
+ imageVerticalSlice = await imageVerticalSlice.extend({
+ top: 0,
+ left: 0,
+ bottom: 0,
+ right: (tileSize - (bufferBound.right - bufferBound.left))
+ });
}
- for (let index = 1; index < segRow.length; index++) {
+ // For every column along this row, join it to the previous column data
+ for (let index: number = 1; index < segRow.length; index++) {
imageVerticalSlice = await imageVerticalSlice
- .overlayWith(tileRow[index],
- {top: 0, left: (bufferBound.right - bufferBound.left) + ((index - 1) * tileSize)});
+ .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]);
- const bufferBound = findRegionToExtract(segments[0][0], desiredRegion);
+ const bufferBound: TileBounds =
+ 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.extend(
- {top: 0, left: 0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0});
+ finalImage = await finalImage
+ .background({
+ r: 0,
+ g: 0,
+ b: 0,
+ alpha: 1
+ }).extend({
+ top: 0,
+ left: 0,
+ bottom: (tileSize - (bufferBound.bottom - bufferBound.top)),
+ right: 0
+ });
}
- for (let index = 1; index < segments.length; index++) {
+ // For all further rows in the image, combine it with the previous rows' data
+ for (let index: number = 1; index < segments.length; index++) {
finalImage = finalImage.overlayWith(
tileVerticalBuffer[index],
{top: getDimension(segments[index - 1][0], 'Y').Size, left: 0});
}
- return finalImage;
-};
+ // Return the finalised image.
+ if ((await finalImage.metadata()).channels != 4) {
+ return sharp(Buffer.alloc(tileSize, tileSize), {
+ create: {
+ width: tileSize,
+ height: tileSize,
+ channels: 4,
+ background: { r: 0, g: 0, b: 0, alpha: 1 }
+ }
+ }).overlayWith(await finalImage.toBuffer())
+ } else {
+ return finalImage;
+ }
+ // .toFile("/cs/home/cjd24/Documents/current/groupPractical/project-code/src/conversion/czi/test1.png");
+}
+
+/**
+ * Used to remove obtuse JSON data,
+ * where it is not needed in the SupportedView object
+ */
+const cleanSupportedViewObject: (obj: parsexml.Node[]) => object = (
+ obj: parsexml.Node[]
+): object => {
+ const newChild: any = {};
+ let hasAttr: boolean = false;
+ let hasChildren: boolean = false;
+ let hasContent: boolean = false;
+
+ // For all nodes in the json object
+ for (const node of obj) {
+
+ // Check if this node has attributes
+ hasAttr = (node.attributes !== undefined
+ && node.attributes !== null
+ && Object.keys(node.attributes).length !== 0
+ );
+ // Check for further children
+ hasChildren = (node.children !== undefined && node.children.length > 0);
+ // Check for simple content object
+ hasContent = (node.content !== undefined
+ && node.content !== null
+ && node.content !== '');
+
+ // If the Node has further children, then deal with this
+ if (hasChildren) {
+ let soloChildren: boolean = true;
+
+ // Check if this node just contains children, or its own data too
+ newChild[node.name] = {};
+ if (hasAttr) {
+ // If there are also attributes, then set this in the output
+ newChild[node.name].attributes = node.attributes;
+ soloChildren = false;
+ }
+ if (hasContent) {
+ // If there is also a 'content' then set this in the output
+ newChild[node.name].content = node.content;
+ soloChildren = false;
+ }
+ // If there are only chilren, then set this as this objects data
+ if (soloChildren) {
+ // Recursively call this function to clean up sub-children too.
+ newChild[node.name] = cleanSupportedViewObject(node.children);
+ } else {
+ // Otherwise, if there is also data, then add a children object
+ newChild[node.name].children = cleanSupportedViewObject(node.children);
+ }
+ } else if (hasAttr) {
+ newChild[node.name] = {};
-//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // Check for content too, if so, add a discrete child for this.
+ if (hasContent) {
+ newChild[node.name].content = node.content;
+ }
+ /*
+ * Add the attributes as a sub child regardless,
+ * since it exists on this key.
+ */
+ newChild[node.name].attributes = node.attributes;
+ } else if (hasContent) {
+ newChild[node.name] = node.content;
+ }
+ }
-const dataBlocks: Segment[] = require(`${extractionDirectory}outputjson.json`).czi.filter(
- (s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty');
-const inspect = require('util').inspect;
-const metaXML: parsexml.Document = parsexml(fs.readFileSync(`${extractionDirectory}FILE-META-1.xml`, 'utf8'));
+ return newChild;
+};
-const supportedViews: SupportedViews = {scalable_image: {width: -1, height: -1, channels: [{channel_id: '-1', channel_name: ''}], metadata: metaXML}};
-supportedViews.scalable_image.channels.pop();
+/**
+ * Clean up all vales of C within the JSON for supported views
+ */
+const cleanSupportedViews: (view: SupportedViews) => void = (
+ view: SupportedViews
+): void => {
+ for (const channel of view.scalable_image.channels) {
+ channel.metadata = cleanSupportedViewObject(
+ channel.metadata as parsexml.Node[]
+ );
+ }
+};
let totalSizeX: number = -1;
let totalSizeY: number = -1;
+const supportedViews: SupportedViews = {
+ scalable_image: {
+ width: -1,
+ height: -1,
+ channels: [{
+ channel_id: '-1',
+ channel_name: ''
+ }],
+ metadata: {}
+ }
+};
+supportedViews.scalable_image.channels.pop();
-// THE FOLLOWING FOR LOOP IS DISGUSTING AND I HATE IT, AND I WISH I DIDNT WRITE IT BUT DON'T SEE ANY OTHER WAY TO DO IT LOL :'(
-for (const child of metaXML.root.children) {
- if (child.name === 'Metadata') {
- for (const entry of child.children) {
- if (entry.name === 'Information') {
- for (const properties of entry.children) {
- if (properties.name === 'Image') {
- for (const property of properties.children) {
- if (property.name === 'SizeX' && property.content) {
- totalSizeX = Number.parseInt(property.content, 10);
- supportedViews.scalable_image.width = totalSizeX;
- continue;
- } else if (property.name === 'SizeY' && property.content) {
- totalSizeY = Number.parseInt(property.content, 10);
- supportedViews.scalable_image.height = totalSizeY;
- continue;
- } else if (property.name === 'Dimensions') {
- for (const chan of property.children) {
- if (chan.name === 'Channels') {
- for (const channel of chan.children) {
- supportedViews.scalable_image.channels.push(
- {
- channel_id: channel.attributes.Id.split(':')[1],
- channel_name: channel.attributes.Name,
- metadata: channel.children
- }
- );
- }
- }
+/* tslint:disable:curly cyclomatic-complexity */
+/*
+ * Function to parse the xml file from the original extraction from CZI,
+ * its nasty!
+ */
+const parseExtractedXML: (xmlFile: string) => void = async(
+ xmlFile: string
+): Promise<void> => {
+ const metaXML: parsexml.Document = parsexml(await readFile(xmlFile, 'utf8'));
+ // Parse the XML :(
+ // THE FOLLOWING 2 FOR LOOPS ARE DISGUSTING AND I HATE IT,
+ // AND I WISH I DIDNT WRITE IT BUT DON'T SEE ANY OTHER WAY TO DO IT LOL :'(
+ for (const child of metaXML.root.children) if (child.name === 'Metadata') {
+ for (const entry of child.children) if (entry.name === 'Information') {
+ for (const properties of entry.children) if (properties.name === 'Image') {
+ for (const property of properties.children) if (
+ property.name === 'SizeX' && property.content
+ ) {
+ totalSizeX = Number.parseInt(property.content, 10);
+ supportedViews.scalable_image.width = totalSizeX;
+ continue;
+ } else if (property.name === 'SizeY' && property.content) {
+ totalSizeY = Number.parseInt(property.content, 10);
+ supportedViews.scalable_image.height = totalSizeY;
+ continue;
+ } else if (property.name === 'Dimensions') {
+ for (const chan of property.children) if (chan.name === 'Channels') {
+ for (const channel of chan.children) {
+ supportedViews.scalable_image.channels.push({
+ channel_id: channel.attributes.Id.split(':')[1],
+ channel_name: channel.attributes.Name,
+ metadata: channel.children
+ });
+ }
+ }
+ }
+ break;
+ }
+ break;
+ }
+ break;
+ }
+ for (const child of metaXML.root.children) if (child.name === 'Metadata') {
+ for (const entry of child.children) if (entry.name === 'Scaling') {
+ for (const properties of entry.children) if (properties.name === 'Items') {
+ for (const dist of properties.children) if (dist.name === 'Distance') {
+ switch (dist.attributes.Id) {
+ case 'X': {
+ supportedViews.scalable_image.real_width = {};
+ for (const attr of dist.children) {
+ if (attr.name === 'Value' && attr.content !== undefined) {
+ supportedViews.scalable_image.real_width.value =
+ Number.parseFloat(attr.content) * 1000000 * totalSizeX;
+ } else if (attr.name === 'DefaultUnitFormat') {
+ supportedViews.scalable_image.real_width.units = attr.content;
+ }
+ }
+ break;
+ }
+ case 'Y': {
+ supportedViews.scalable_image.real_height = {};
+ for (const attr of dist.children) {
+ if (attr.name === 'Value' && attr.content !== undefined) {
+ supportedViews.scalable_image.real_height.value =
+ Number.parseFloat(attr.content) * 1000000 * totalSizeY;
+ } else if (attr.name === 'DefaultUnitFormat') {
+ supportedViews.scalable_image.real_height.units = attr.content;
}
}
+ break;
}
}
}
+ break;
}
+ break;
}
+ break;
}
-}
+ supportedViews.scalable_image.metadata = metaXML;
+};
+/* tslint:enable:curly cyclomatic-complexity */
-// Get all values of X and Y respectively.
-const uniqueX: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'X').Start).filter(
- (item: number, index: number, array: number[]) => array.indexOf(item) === index);
-const uniqueY: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'Y').Start).filter(
- (item: number, index: number, array: number[]) => array.indexOf(item) === index);
-
-const uniqueTileSizes: number[][] = [];
-for (const seg of dataBlocks) {
-
- const x: number = getDimension(seg, 'X').Size;
- const y: number = getDimension(seg, 'Y').Size;
- let found: boolean = false;
- for (const dimPair of uniqueTileSizes) {
- if (x === dimPair[0] && y === dimPair[1]) {
- found = true;
- break;
+////////////////////////////////////////////////////////////////////////////////
+// Begin work on getting the new tiles all nice
+////////////////////////////////////////////////////////////////////////////////
+
+/**
+ * This is used to create the next zoomed out tier of the given height map
+ */
+const zoomTier: (
+ previousHeightMap: CZIHeightMap, p: number, c: number
+) => Promise<CZIHeightMap> = async(
+ previousHeightMap: CZIHeightMap, p: number, c: number
+): Promise<CZIHeightMap> => {
+
+ const squashRow = async (previousPlane: CZITile[][], ys: number, p: number): Promise<CZITile[]> => {
+
+ const squashQuad = async (previousPlane: CZITile[][], ys: number, xs: number, p: number): Promise<CZITile> => {
+ if (await exists(`${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`) && (ys < previousPlane.length)) {
+ finalCZIJson.total_files++;
+ return {
+ x_offset: xs * tileSize,
+ y_offset: ys * tileSize,
+ width: tileSize,
+ height: tileSize,
+ file: `img-c${c}-p${p}-y${ys}-x${xs}.png`
+ };
+ }
+
+ // Combine 4 tiles into a new tile and scale down for this tier
+ // Top left
+ let quadrents:string = `${outputImageDirectory}${previousPlane[ys][xs].file} `;
+ let across:number = 1;
+ let quadrentCount: number = 1;
+
+ // Combine top right
+ const moreToRight: boolean = (xs + 1) < previousPlane[0].length;
+ if (moreToRight) {
+ quadrents += `${outputImageDirectory}${previousPlane[ys][xs + 1].file} `;
+ across++; quadrentCount++;
+ }
+ // Combine bottom left
+ const moreToBottom: boolean = (ys + 1) < previousPlane.length;
+ if (moreToBottom) {
+ quadrents += `${outputImageDirectory}${previousPlane[ys + 1][xs].file} `;
+ quadrentCount++;
+ }
+ // Combine bottom right
+ if (moreToBottom && moreToRight) {
+ quadrents += `${outputImageDirectory}${previousPlane[ys + 1][xs + 1].file} `;
+ }
+
+ let outputFileName: string =`${outputImageData}/tmp/${uuid.generate()}.png`;
+ shell.exec(`${execpaths} vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`, {silent: true});
+
+ // Rescale and push to file
+ if (quadrentCount !== 3) {
+
+ let extRight: number = 0, extBottom: number = 0;
+ if (moreToRight) {
+ extBottom = tileSize;
+ } else if (moreToBottom){
+ extRight = tileSize;
+ }
+
+ sharp(await sharp(outputFileName)
+ .background({r: 0, g: 0, b: 0, alpha: 1})
+ .extend({
+ top: 0, left: 0,
+ bottom: extBottom, right: extRight
+ }).toBuffer())
+ .resize(tileSize, tileSize)
+ .toFile(`${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`);
+ } else {
+ await sharp(outputFileName)
+ .resize(tileSize, tileSize)
+ .toFile(`${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`);
+ }
+ shell.exec(`rm ${outputFileName}`, {silent: true});
+
+ finalCZIJson.total_files++;
+ return {
+ x_offset: previousPlane[ys][xs].x_offset,
+ y_offset: previousPlane[ys][xs].y_offset,
+ width: previousPlane[ys][xs].width * 2,
+ height: previousPlane[ys][xs].height * 2,
+ file: `img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`
+ };
+ }
+
+ const cziRow: Promise<CZITile>[] = [];
+ // For all columns within the previous plane
+ for (let xs: number = 0; xs < previousPlane[0].length; xs += 2) {
+ cziRow.push(squashQuad(previousPlane, ys, xs, p));
}
+
+ return await Promise.all(cziRow);
}
- if (!found) {
- uniqueTileSizes.push([x, y]);
+
+ const newZoomTier: CZIHeightMap = {
+ zoom_level: previousHeightMap.zoom_level * 2, plane: []
+ };
+
+ // Check the condition where another zoom level does not make sense
+ if (previousHeightMap.plane.length === 1
+ && previousHeightMap.plane[0].length === 1) {
+ console.log(
+ ' Task(1/1): ' +
+ 'Stage 100% complete. ' +
+ 'Stage was skipped as maximum sensible zoom level was reached.'
+ );
+ return previousHeightMap;
}
-}
-let filteredDataBlocks: Segment[] = [];
-const filterC: Function = function(to: number): void {
- filteredDataBlocks = dataBlocks.filter(
- (item: Segment, index: number, array: Segment[]) => getDimension(item, 'C').Start === to
- );
-};
+ const newplane: CZITile[][] = [];
+ // For all rows within the previous plane
+ for (let ys: number = 0; ys < previousHeightMap.plane.length; ys += 2) {
+ newplane.push(await squashRow(previousHeightMap.plane, ys, p));
+
+ console.log(
+ ` Task(${ys / 2 + 1}/${
+ Math.floor(previousHeightMap.plane.length / 2) + 1}): ` +
+ `Stage ${Math.ceil(((ys / previousHeightMap.plane.length)
+ * 100) * 100) / 100}% complete. `
+ );
+ }
-////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ newZoomTier.plane = newplane;
+ newZoomTier.tile_height_count = newZoomTier.plane.length;
+ newZoomTier.tile_width_count = newZoomTier.plane[0].length;
-// Begin work on getting the new tiles all nice
-// Print out all of the related tiles to every new tile to be created.
-let filecoutner: number = 0;
-async function extrapolateDimension(cVal: number, totalCs: number, maxZoomLevel: number): Promise<CZIHeightMap[]> {
- console.log(`Stage (${cVal + 1}/${totalCs}): Task(0/${Math.ceil(totalSizeY / tileSize)}): 0% complete.`);
- for (let ys: number = 0; ys < totalSizeY;) {
- let timing = process.hrtime();
- for (let xs: number = 0; xs < totalSizeX; xs += tileSize) {
- const desired = new TileBounds (
+ return newZoomTier;
+};
+
+/**
+ * Big boi function to build up the base tier of each value of c, then builds
+ * Our pre-computed pyramid of the rest of the zoom levels.
+ */
+const extrapolateDimension: (
+ cVal: number, totalCs: number, maxZoom: number
+) => Promise<CZIHeightMap[]> = async(
+ cVal: number, totalCs: number, maxZoom: number
+): Promise<CZIHeightMap[]> => {
+
+ const doOneRow = (ys: number, filteredDataBlocks: Segment[]): Promise<CZITile[]> => {
+
+ const doOneBaseTile = async(xs: number, ys: number, filteredDataBlocks: Segment[]): Promise<CZITile> => {
+ if (await exists(`${outputImageDirectory}img-c${cVal}-p0-y${ys}-x${xs}.png`) && (ys + tileSize < totalSizeY)) {
+ ///////////////////////////////////////////////////////////////////////////////////This if statement should be temporary??????????????????????????????????/
+ finalCZIJson.total_files++;
+ return {
+ x_offset: xs,
+ y_offset: ys,
+ width: tileSize,
+ height: tileSize,
+ file: `img-c${cVal}-p0-y${ys}-x${xs}.png`
+ };
+ }
+ const desired: TileBounds = new TileBounds(
xs - tileOverlap,
xs + tileSize + tileOverlap,
ys - tileOverlap,
ys + tileSize + tileOverlap
);
- filterC(cVal);
- // console.log(filteredDataBlocks.map((x: any) => x.Data.DirectoryEntry.DimensionEntries[2]));
- const sortedSegments: Segment[][] = orderSegments(findRelatedTiles(filteredDataBlocks, desired));
- (await extractAndStitchChunks(sortedSegments, desired)).toFile(`${outputImageDirectory}img-${filecoutner++}`);
+ const sortedSegments: Segment[][] =
+ orderSegments(findRelatedTiles(filteredDataBlocks, desired));
+
+ (await extractAndStitchChunks(sortedSegments, desired))
+ .toFile(`${outputImageDirectory}img-c${cVal}-p0-y${ys}-x${xs}.png`);
+
+ return {
+ x_offset: xs,
+ y_offset: ys,
+ width: tileSize,
+ height: tileSize,
+ file: `img-c${cVal}-p0-y${ys}-x${xs}.png`
+ };
+ }
+
+ const rowPromises: Promise<CZITile>[] = [];
+
+ for (let xs: number = 0; xs < totalSizeX; xs += tileSize) {
+ rowPromises.push(doOneBaseTile(xs, ys, filteredDataBlocks));
+ finalCZIJson.total_files++;
}
- ys += tileSize;
- timing = process.hrtime(timing);
- console.log(`Stage (${cVal + 1}/${totalCs}): Task(${ys / tileSize}/${Math.ceil(totalSizeY / tileSize)}): ${Math.ceil(((ys / totalSizeY) * 100) * 100) / 100}% complete. (${timing[0]} sec/iter)`);
+
+ return Promise.all(rowPromises);
}
- return [];
-}
-const finalCZIJson: WholeCZIHierarchy = {} as any;
-async function main(): Promise<void> {
- for (const cval of supportedViews.scalable_image.channels) {
- await extrapolateDimension(Number.parseInt(cval.channel_id, 10), supportedViews.scalable_image.channels.length, maxZoom).then((v) => {
- finalCZIJson.c_values.push({channel_id: cval.channel_id, height_map: v});
- console.log(`Completed Tier: ${cval.channel_id}`);
+ const filteredDataBlocks: Segment[] = dataBlocks.filter(
+ (item: Segment, index: number, array: Segment[]) =>
+ getDimension(item, 'C').Start === cVal
+ );
+ // Begin output for the base tier
+ console.log('=========================================================');
+ console.log(`>> Beginning Dimension Extrapolation for \'C\' : ${cVal}`);
+ console.log('=========================================================');
+ console.log('>> Computing base tier, this will take a while...\n');
+ const baseCZIHeightMap: CZIHeightMap = {zoom_level: 1, plane: []};
+
+ console.log(`Stage (${cVal * Math.log2(maxZoom) + 1}/${totalCs}):`);
+ // For all rows within the total base pixel height
+ const plane: CZITile[][] = [];
+ for (let ys: number = 0; ys < totalSizeY; ys += tileSize) {
+ plane.push(await doOneRow(ys, filteredDataBlocks));
+
+ process.stdout.write("\r");
+ console.log(
+ ` Task(${ys / tileSize}/${Math.ceil(totalSizeY / tileSize)}): ` +
+ `Stage ${Math.ceil(((ys / totalSizeY) * 100) * 100) / 100}% complete. `
+ );
+ }
+ baseCZIHeightMap.plane = plane;
+ baseCZIHeightMap.tile_height_count = baseCZIHeightMap.plane.length;
+ baseCZIHeightMap.tile_width_count = baseCZIHeightMap.plane[0].length;
+
+ // BUILD UP THE HIGHER ZOOM LAYERS.
+ console.log(`>> Base tier complete for \'C\': ${cVal
+ }; Begin computing zoom tiers...\n`);
+
+ const retHeightMap: CZIHeightMap[] = [baseCZIHeightMap];
+ writeJSONToFile(`${outputImageData}/intermediate-stage-map.json`, retHeightMap);
+ for (let stage: number = 1; stage <= Math.log2(maxZoom); stage++) {
+ console.log(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`);
+ await zoomTier(retHeightMap[stage - 1], stage, cVal)
+ .then((v: CZIHeightMap) => {
+ retHeightMap.push(v);
return;
- }, (err) => {
- console.error(err);
}
);
+ writeJSONToFile(`${outputImageData}/intermediate-stage-map.json`, retHeightMap);
+ }
+
+ console.log(`>> Completed Extrapolation for dimension, \'C\': ${cVal}\n\n`);
+ return retHeightMap;
+};
+
+
+/**
+ * used to write the supported views object to file both in total and "cleaned"
+ */
+const createSupportedViewsObject: () => void = async(): Promise<void> => {
+ dataBlocks = require(`${extractDirectory}outputjson.json`)
+ .czi.filter((s: Segment) =>
+ s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'
+ );
+ // Parse the xml
+ await parseExtractedXML(`${extractDirectory}FILE-META-1.xml`);
+
+ // Create the total supported Views object
+ // !!!!! This line was removed in order to reduce the output file size and
+ // !!!!! increase the usability by only giving the striped down version
+ // writeJSONToFile(`${outputImageData}/supported_views.json`, supportedViews);
+
+ // Cleanup and create "smart" supported views object without whole metadata
+ cleanSupportedViews(supportedViews);
+ supportedViews.scalable_image.metadata = {
+ tile_size: tileSize,
+ max_zoom: maxZoom,
+ tile_overlap: tileOverlap
+ };
+ writeJSONToFile(
+ `${outputImageData}/supported_views.json`, supportedViews);
+};
+
+/**
+ * Used to build up a pyramid for each value of c from the base images
+ */
+const buildCustomPyramids: () => Promise<boolean> = async(): Promise<boolean> => {
+ // Set some variables for errors and and percent counts
+ let errorOccurred: boolean = false;
+ finalCZIJson.zoom_level_count = Math.log2(maxZoom) + 1;
+
+ // For all channels in the base image
+ for (const cval of supportedViews.scalable_image.channels) {
+
+ errorOccurred = false;
+ if (!errorOccurred) {
+ // Extract the base tiles and build up custom pyramid data
+ await extrapolateDimension(
+ Number.parseInt(cval.channel_id, 10),
+ supportedViews.scalable_image.channels.length * Math.log2(maxZoom * 2),
+ maxZoom
+ ).then((v: CZIHeightMap[]) => {
+ // On success, add the new heightmap to the final json data block
+ finalCZIJson.c_values.push({channel_id: cval.channel_id, height_map: v});
+ finalCZIJson.c_value_count++;
+ return;
+ }).catch((err: Error) => {
+ // On error, write the error to console and set an error true.
+ if (err) {
+ console.error(err.message);
+ }
+ errorOccurred = true;
+ }
+ );
+ } else {
+ console.error(`\nAn error occurred while extracting dimension: ${cval}`);
+ console.error('Skipping futher elements and moving to next dimension.\n\n');
+ }
+ // Write the final json data to file with most recent changes
+ writeJSONToFile(`${outputImageData}/layout.json`, finalCZIJson);
}
- fs.writeFile(`${outputImageDirectory}layout.json`, JSON.stringify(finalCZIJson), (err) => console.error(err));
+ finalCZIJson.complete = true;
+ return errorOccurred;
+};
+
+const initialExtractAndConvert: (absFilePath: string) => Promise<void> = async (absFilePath: string): Promise<void> => {
+
+ outputImageData = `${absFilePath.split('.')[0]}-processed`;
+ extractDirectory = outputImageData + "/extract/";
+ outputImageDirectory = outputImageData + "/data/";
+
+ checkForOutputDirectories([outputImageData, extractDirectory]);
+ console.log(">> This will complete at roughly 2GB/min");
+ shell.exec(`${execpaths} CZICrunch ${absFilePath} ${extractDirectory}`);
+
+ shell.exec(`${execpaths} python3 convertJxrs.py ${extractDirectory}`);
+
+ // let totalFiles: number = 0, counter: number = 0;
+ // console.log("=========== BEGIN JXR CONVERSION ===========")
+ //
+ // let filenames: string[] = (await readdir(extractDirectory)).filter((x: string) => x.endsWith(".jxr"));
+ // counter = 0
+ // totalFiles = filenames.length;
+ //
+ // const doOne: (n: number, file: string, asTif: string) => Promise<void> = async(n: number, file: string, asTif: string): Promise<void> => {
+ // shell.exec(`${execpaths} JxrDecApp -i ${file} -o ${asTif}`);
+ // shell.exec(`convert ${asTif} ${file.substring(0, file.lastIndexOf('.'))}.png`);
+ // shell.exec(`rm ${file} ${asTif}`);
+ // console.log (`> Processed File: ${n}/${totalFiles} : ${file} --> ${file.substring(0, file.lastIndexOf('.'))}.png`);
+ // }
+ //
+ // try {
+ // let promises: Promise<void>[] = [];
+ // for (let index: number = 0; index < filenames.length; index++) {
+ //
+ // if (promises.length < 30) {
+ // let file = extractDirectory + filenames[index];
+ // promises.push(doOne(counter++, file, file.substring(0, file.lastIndexOf('.')) + ".tif"));
+ // } else {
+ // index--;
+ // await Promise.all(promises);
+ // promises.length = 0;
+ // }
+ // }
+ // await Promise.all(promises);
+ // } catch (err) {
+ // console.log("Processing Failed. Probably couldn't find decoder due to invalid system environment path, check this before debugging. Actual Err:");
+ // console.error(err);
+ // }
+ // console.log("=========== FINISH JXR CONVERSION ===========")
}
+
+process.on("warning", (err: any) => console.warn(err))
+/**
+ * Main function used to call the rest of the relevant code to crunch a CZI
+ * extraction.
+ */
+const main: () => Promise<void> = async (): Promise<void> => {
+ console.log('\n');
+
+ try {
+ console.log('>> Extracting from CZI and Converting to PNG');
+ await initialExtractAndConvert(testFile);
+
+ console.log('\n>> Checking/Creating output directories...');
+ checkForOutputDirectories([outputImageDirectory, `${outputImageData}/tmp/`]);
+
+ console.log('\n>> Creating Supported Views and writing files...');
+ await createSupportedViewsObject();
+
+ console.log('\n');
+ if (await buildCustomPyramids()) {
+ console.log('>> Removing the initial extraction bloat');
+ shell.exec(`rm -rf ${outputImageData}/extract/`, { async: true })
+ };
+
+ console.log("\n>> Done");
+ } catch (Err) {
+ console.error("This was a really big boi error, and something is sad: ");
+ console.error(Err);
+ }
+};
main();
+
+// /* tslint:disable */
+// async function main2() {
+//
+// let layout: WholeCZIHierarchy = require(`${outputImageData}layout.json`);
+//
+// for (let stage:number = 1; stage < Math.sqrt(maxZoom); stage++) {
+// await zoomTier(layout.c_values[0].height_map[stage - 1])
+// .then((v: CZIHeightMap) =>
+// {
+// writeJSONToFile(`${outputImageData}stageMap-${stage}.json`, v);
+// return;
+// }
+// );
+// }
+// }
+//
+// main2().then().catch(e => console.log(e));
diff --git a/src/conversion/czi/cziConvert.sh b/src/conversion/czi/cziConvert.sh
index 639251c..dd664d5 100755
--- a/src/conversion/czi/cziConvert.sh
+++ b/src/conversion/czi/cziConvert.sh
@@ -1,8 +1,11 @@
#!/bin/sh
+FILENAME='2016_12_17__0701'
CZI_WORKING_DIR=${1:-"/cs/scratch"}
-CZI_EXTRACTION_DIR=${2:-"0701-extraction"}
-CZI_FILE=${3:-"2016_12_17__0701.czi"}
+CZI_EXTRACTION_DIR=${2:-${FILENAME}}
+CZI_FILE=${3:-${FILENAME}".czi"}
+
+echo "about to try to convert: " + ${CZI_WORKING_DIR}/${USER}/${CZI_FILE}
gcc -Wall -Wextra --pedantic -std=c99 cziconvert.c
mkdir -p ${CZI_WORKING_DIR}/${USER}/${CZI_EXTRACTION_DIR}
diff --git a/src/conversion/czi/cziconvert.c b/src/conversion/czi/cziconvert.c
index 85b925c..3024e7c 100644
--- a/src/conversion/czi/cziconvert.c
+++ b/src/conversion/czi/cziconvert.c
@@ -284,8 +284,8 @@ int functionRouter(FILE* imageFile, FILE* jsonOutput, long* fileOffset) {
int main(int argc, char* argv[]) {
//Check program input arguments.
- if (argc < 2 || argc > 4) {
- printf("Invalid number of arguments passed in.\nUsage:\n\n./prog <input file> <outputjson> <pythonJxrConvertor>\n\n");
+ if (argc < 2 || argc > 3) {
+ printf("Invalid number of arguments passed in.\nUsage:\n\n./prog <input file> <outputjson>\n\n");
exit(1);
}
@@ -340,15 +340,5 @@ int main(int argc, char* argv[]) {
fclose(jsonOutput);
printf("\n=========== FINISH CZI EXTRACTION ===========\n\n\n\n");
-
- //convert all the data's to jxr;
- char jxrLoc[200];
- sprintf(jxrLoc, "%s %s %s", "python3", argv[3], argv[2]);
- system(jxrLoc);
-
-
- //begin work on re-factoring the image structure into a "smooth" grid
-
-
return 0;
}
diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts
new file mode 100644
index 0000000..5e6911c
--- /dev/null
+++ b/src/conversion/czi/pyramidWorker.ts
@@ -0,0 +1,76 @@
+import { CZIHeightMap, CZITile, CZITileRequest } from '../types/customPyramidIndex';
+import { TileBounds, execpaths } from '../types/helpers';
+import * as sharp from 'sharp';
+import { isTileRelated } from './tileExtraction';
+import { uuid } from '../../uuid'
+
+const findRelatedTiles: Function = function(plane: CZIHeightMap, desired: TileBounds): CZITile[][] {
+
+ const relatedTiles: CZITile[][] = [];
+ for (const planeTileRow of plane.plane) {
+ let tileRow: CZITile[] = [];
+ let 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 getFinalTile: Function = async function(imageDir: string, imageTier: CZIHeightMap, cVal: string, desiredRegion: TileBounds): Promise<CZITileRequest> {
+
+ console.error("Has the calling function checked that the image has completed processing in WholeCZIHierarchy??");
+
+ let involvedTiles: string = '';
+ for (const row of imageTier.plane) {
+ for (const tile of row) {
+ involvedTiles += `${imageDir}/data/${tile.file} `
+ }
+ }
+
+ let outputFileName: string =`${imageDir}/tmp/${uuid.generate()}.png`
+ require('shelljs').exec(`${execpaths} vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${imageTier.plane[0].length}`)
+
+ let extractionRegion = new TileBounds(
+ desiredRegion.left - imageTier.plane[0][0].width,
+ desiredRegion.right - imageTier.plane[0][0].width,
+ desiredRegion.top - imageTier.plane[0][0].height,
+ desiredRegion.bottom - imageTier.plane[0][0].height
+ );
+ extractionRegion.scaleDown(imageTier.zoom_level);
+
+ await sharp(outputFileName)
+ .extract({
+ top: extractionRegion.top,
+ left: extractionRegion.left,
+ width: extractionRegion.width(),
+ height: extractionRegion.height()
+ })
+ .toFile(outputFileName);
+
+ return {
+ dimensions: new TileBounds(
+ 0, extractionRegion.width(),
+ 0, extractionRegion.height()
+ ),
+ original_bounds: desiredRegion,
+ zoom_level: imageTier.zoom_level,
+ c_value: cVal,
+ file_path: outputFileName
+ };
+}
diff --git a/src/conversion/czi/tileDims.png b/src/conversion/czi/tileDims.png
new file mode 100644
index 0000000..70e2484
--- /dev/null
+++ b/src/conversion/czi/tileDims.png
Binary files differ
diff --git a/src/conversion/czi/tileExtraction.ts b/src/conversion/czi/tileExtraction.ts
new file mode 100644
index 0000000..83f63a5
--- /dev/null
+++ b/src/conversion/czi/tileExtraction.ts
@@ -0,0 +1,122 @@
+import { TileBounds } from '../types/helpers';
+
+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, zoomLevel: number): TileBounds {
+
+ //get the base tile area and create an object for the chunk to extract
+ const 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).');
+ }
+
+ chunkToExtract.left = Math.ceil(chunkToExtract.left / zoomLevel);
+ chunkToExtract.right = Math.ceil(chunkToExtract.right / zoomLevel);
+ chunkToExtract.top = Math.ceil(chunkToExtract.top / zoomLevel);
+ chunkToExtract.bottom = Math.ceil(chunkToExtract.bottom / zoomLevel);
+
+ //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;
+// }