From 32dede1bd9b84b46ffba8939cdb98641d06c4f20 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Fri, 20 Apr 2018 22:02:44 +0100 Subject: Seems to have got the big boi CZI working again, added support for lecia files --- src/conversion/czi/czi.ts | 92 +++++++++++----------------- src/conversion/czi/cziConvert.sh | 2 + src/conversion/czi/pyramidWorker.ts | 4 +- src/conversion/czi/tileExtraction.ts | 2 +- src/conversion/leica/requestconvertor.ts | 1 + src/conversion/leica/scn.ts | 100 ++++++++++++++++++++++++++++++ src/conversion/types/helperCZITypes.ts | 66 -------------------- src/conversion/types/helpers.ts | 102 +++++++++++++++++++++++++++++++ 8 files changed, 245 insertions(+), 124 deletions(-) create mode 100644 src/conversion/leica/requestconvertor.ts create mode 100644 src/conversion/leica/scn.ts delete mode 100644 src/conversion/types/helperCZITypes.ts create mode 100644 src/conversion/types/helpers.ts (limited to 'src') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index c10a6f7..1d157ff 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -2,7 +2,7 @@ import { CZIHeightMap, CZITile, WholeCZIHierarchy } from '../types/customPyramidIndex'; import { Dimension, Segment } from '../types/cziBinaryTypings'; import * as fs from 'fs'; -import { SupportedViews, TileBounds } from '../types/helperCZITypes'; +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 @@ -13,7 +13,6 @@ import { uuid } from '../../uuid' // Various constants for placing files and defining tiles const baseDirname: string = '/cs/scratch/cjd24/0701-extraction'; -const extensionBinariesDir: string = __dirname + `/../../../ext/bin/`; const extractionDirectory: string = `${baseDirname}/`; const outputImageData: string = `${baseDirname}-processed/`; const outputImageDirectory: string = `${baseDirname}-processed/data/`; @@ -189,9 +188,9 @@ const findRegionToExtract: ( * into a new image */ const extractAndStitchChunks: ( - segments: Segment[][], desiredRegion: TileBounds + segments: Segment[][], desiredRegion: TileBounds, tmp: number ) => Promise = async( - segments: Segment[][], desiredRegion: TileBounds + segments: Segment[][], desiredRegion: TileBounds, tmp: number ): Promise => { // Create a buffer for the rows part of raw image data @@ -254,17 +253,18 @@ const findRegionToExtract: ( 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 - }); + 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: number = 1; index < segments.length; index++) { @@ -274,8 +274,16 @@ const findRegionToExtract: ( } // Return the finalised image. - return finalImage; -}; + return sharp(Buffer.alloc(1,1), { + create: { + width: tileSize, + height: tileSize, + channels: 4, + background: { r: 0, g: 0, b: 0, alpha: 0 } + } + }).overlayWith(await finalImage.toBuffer()) + // .toFile("/cs/home/cjd24/Documents/current/groupPractical/project-code/src/conversion/czi/test1.png"); +} /** * Used to remove obtuse JSON data, @@ -532,7 +540,8 @@ const zoomTier: ( } let outputFileName: string =`${outputImageData}tmp/${uuid.generate()}.png`; - shell.exec(`${extensionBinariesDir}vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`); +// console.log(quadrents); + shell.exec(`${execpaths} vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`); // Rescale and push to file await sharp(outputFileName) @@ -601,7 +610,8 @@ const extrapolateDimension: ( for (; ys < totalSizeY;) { timing = process.hrtime(); const cziRow: CZITile[] = []; - process.stdout.write(`${Math.ceil(totalSizeX/tileSize)} : `); + let rowProgBar: string = `${Math.ceil(totalSizeX/tileSize)} : `; + let rowProgCount: number = 0; for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { const desired: TileBounds = new TileBounds( xs - tileOverlap, @@ -620,10 +630,12 @@ const extrapolateDimension: ( const sortedSegments: Segment[][] = orderSegments(findRelatedTiles(filteredDataBlocks, desired)); - (await extractAndStitchChunks(sortedSegments, desired)) - .toFile(`${outputImageDirectory}img-${filecounter++}`); + (await extractAndStitchChunks(sortedSegments, desired, filecounter)) + .toFile(`${outputImageDirectory}img-${filecounter++}.png`); +// shell.exec(`${execpaths} vips addalpha "${outputImageDirectory}img-${filecounter}" "${outputImageDirectory}img-${filecounter++}"`); - process.stdout.write(">"); + rowProgBar += ">"; rowProgCount++; + process.stdout.write(`\r${rowProgBar} ${rowProgCount}`); finalCZIJson.total_files++; } baseCZIHeightMap.plane.push(cziRow); @@ -651,7 +663,7 @@ const extrapolateDimension: ( const retHeightMap: CZIHeightMap[] = [baseCZIHeightMap]; writeJSONToFile(`${outputImageData}stageMap-${cVal}-${0}`, retHeightMap); - for (let stage: number = 1; stage < Math.log2(maxZoom); stage++) { + 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]) .then((v: CZIHeightMap) => { @@ -666,35 +678,6 @@ const extrapolateDimension: ( return retHeightMap; }; -/** - * function used to ensure that the directories required have been created - */ -const checkForOutputDirectories: (directories: string[]) => void = ( - directories: string[] -): void => { - for (const dir of directories) { - if (!fs.existsSync(`${dir}`)) { - fs.mkdirSync(`${dir}`); - } - } -}; - -/** - * Write given JSON object to given filepath - */ -const writeJSONToFile: (filePath: string, obj: object) => - void = (filePath: string, obj: object): void => { - fs.writeFile( - filePath, - JSON.stringify(obj, null, 2), - (err: Error) => { - if (err) { - console.error(err.message); - throw err; - } - } - ); - }; /** * used to write the supported views object to file both in total and "cleaned" @@ -787,17 +770,16 @@ main(); // async function main2() { // // let layout: WholeCZIHierarchy = require(`${outputImageData}layout.json`); -// filecounter = 5530; // // 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); +// writeJSONToFile(`${outputImageData}stageMap-${stage}.json`, v); // return; // } // ); // } // } // -// main2().then(); +// main2().then().catch(e => console.log(e)); diff --git a/src/conversion/czi/cziConvert.sh b/src/conversion/czi/cziConvert.sh index 2529d44..dd664d5 100755 --- a/src/conversion/czi/cziConvert.sh +++ b/src/conversion/czi/cziConvert.sh @@ -5,6 +5,8 @@ CZI_WORKING_DIR=${1:-"/cs/scratch"} 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} ./a.out ${CZI_WORKING_DIR}/${USER}/${CZI_FILE} ${CZI_WORKING_DIR}/${USER}/${CZI_EXTRACTION_DIR}/ ${PWD}/convertJxrs.py diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts index 19acbf9..5e6911c 100644 --- a/src/conversion/czi/pyramidWorker.ts +++ b/src/conversion/czi/pyramidWorker.ts @@ -1,5 +1,5 @@ import { CZIHeightMap, CZITile, CZITileRequest } from '../types/customPyramidIndex'; -import { TileBounds } from '../types/helperCZITypes'; +import { TileBounds, execpaths } from '../types/helpers'; import * as sharp from 'sharp'; import { isTileRelated } from './tileExtraction'; import { uuid } from '../../uuid' @@ -44,7 +44,7 @@ const getFinalTile: Function = async function(imageDir: string, imageTier: CZIHe } let outputFileName: string =`${imageDir}/tmp/${uuid.generate()}.png` - require('shelljs').exec(`vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${imageTier.plane[0].length}`) + require('shelljs').exec(`${execpaths} vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${imageTier.plane[0].length}`) let extractionRegion = new TileBounds( desiredRegion.left - imageTier.plane[0][0].width, diff --git a/src/conversion/czi/tileExtraction.ts b/src/conversion/czi/tileExtraction.ts index a768f6e..83f63a5 100644 --- a/src/conversion/czi/tileExtraction.ts +++ b/src/conversion/czi/tileExtraction.ts @@ -1,4 +1,4 @@ -import { TileBounds } from '../types/helperCZITypes'; +import { TileBounds } from '../types/helpers'; export const isTileRelated: Function = function(origCoords: TileBounds, desired: TileBounds): boolean { diff --git a/src/conversion/leica/requestconvertor.ts b/src/conversion/leica/requestconvertor.ts new file mode 100644 index 0000000..50002d7 --- /dev/null +++ b/src/conversion/leica/requestconvertor.ts @@ -0,0 +1 @@ +import { logger } from '../../logger'; diff --git a/src/conversion/leica/scn.ts b/src/conversion/leica/scn.ts new file mode 100644 index 0000000..e2125e1 --- /dev/null +++ b/src/conversion/leica/scn.ts @@ -0,0 +1,100 @@ +import * as fs from 'fs'; +import * as sharp from 'sharp'; +// tslint:disable-next-line:no-duplicate-imports +import { SharpInstance } from 'sharp'; +import { SupportedViews, TileBounds, writeJSONToFile, checkForOutputDirectories } from '../types/helpers'; +import { uuid } from '../../uuid' +import { logger } from '../../logger'; + +// CHANGE ME FOR TESTING!!!!! +const input: string = "test.tiff" +const baseDirname: string = '/cs/scratch/cjd24/tifers/'; + + + +// Various constants for placing files and defining tiles +const extensionBinariesDir: string = __dirname + `/../../../ext/bin/`; +const execpaths: string = `PATH="$PATH:${extensionBinariesDir}" LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${extensionBinariesDir}../lib/" `; + +const tileOverlap: number = 0; // Overlap is only half implemented +const tileSize: number = 512; + + +const crunchLeica: () => void = async (): Promise => { + + try { + let output: string =`${baseDirname}${uuid.generate()}/`; + let leica: SharpInstance = sharp(baseDirname + input).png(); + logger.debug("Read new sharp instance for lecia: " + input); + + checkForOutputDirectories([output]); + logger.info("Creating new output directory for LECIA > DZI @ " + output); + + let meta: sharp.Metadata = await leica.metadata(); + + let width: number = -1; + let height: number = -1; + if (meta.width !== undefined) { + width = meta.width; + } + if (meta.height !== undefined) { + height = meta.height; + } + + let supportedViews: SupportedViews = { + scalable_image: { + width: width, + height: height, + channels: + [{ + channel_id: '-1', + channel_name: '-1', + metadata: {} + }], + metadata: { + tile_size: tileSize, + max_zoom: "Not yet supported in this version of convertor", + tile_overlap: tileOverlap, + exif: meta.exif + } + } + } + + let channels: any = []; + if (meta.channels !== undefined) { + for (let index: number = 0; index < meta.channels; index++) { + channels.push({ + channel_id: `${index}`, + channel_name: `${meta.space}`, + metadata: {} + }) + } + supportedViews.scalable_image.channels = channels; + } + + writeJSONToFile(`${output}supported_views.json`, supportedViews) + logger.info("Wrote supported_views object for: " + output); + + await sharp(baseDirname + input) + .png() + .tile({ + size: tileSize, + overlap: tileOverlap, + layout: "dz" + }) + .toFile(`${output}output.dzi`); + logger.success(`Finalised output of ${input} as .dzi`); + } + catch (err) { + logger.failure(`Lecia conversion failed with error: ${err}`) + } +}; + +/** + * Main function used to call the rest of the relevant code to crunch a CZI + * extraction. + */ +const main: () => void = (): void => { + crunchLeica(); +}; +main(); diff --git a/src/conversion/types/helperCZITypes.ts b/src/conversion/types/helperCZITypes.ts deleted file mode 100644 index 8f6310a..0000000 --- a/src/conversion/types/helperCZITypes.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { Node } from 'xml-parser'; - -/** - * Interface used to define the structure of the "supportedViews" section - * of the protocol specification for scalable images - */ -export 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 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; - } - public width(): number { - return this.right - this.left; - } - public height(): number { - return this.bottom - this.top; - } - public scaleDown(level: number) { - this.left = Math.ceil(this.left / level), - this.right = Math.ceil(this.right / level), - this.top = Math.ceil(this.top / level), - this.bottom = Math.ceil(this.bottom / level) - } - public scaleUp(level: number) { - this.left = Math.floor(this.left * level), - this.right = Math.ceil(this.right * level), - this.top = Math.ceil(this.top * level), - this.bottom = Math.ceil(this.bottom * level) - } -} diff --git a/src/conversion/types/helpers.ts b/src/conversion/types/helpers.ts new file mode 100644 index 0000000..8e07944 --- /dev/null +++ b/src/conversion/types/helpers.ts @@ -0,0 +1,102 @@ +import * as fs from 'fs'; +import { Node } from 'xml-parser'; + +/** + * Interface used to define the structure of the "supportedViews" section + * of the protocol specification for scalable images + */ +export 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 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; + } + public width(): number { + return this.right - this.left; + } + public height(): number { + return this.bottom - this.top; + } + public scaleDown(level: number) { + this.left = Math.ceil(this.left / level), + this.right = Math.ceil(this.right / level), + this.top = Math.ceil(this.top / level), + this.bottom = Math.ceil(this.bottom / level) + } + public scaleUp(level: number) { + this.left = Math.floor(this.left * level), + this.right = Math.ceil(this.right * level), + this.top = Math.ceil(this.top * level), + this.bottom = Math.ceil(this.bottom * level) + } +} + + + +/** + * function used to ensure that the directories required have been created + */ +export const checkForOutputDirectories: (directories: string[]) => void = ( + directories: string[] +): void => { + for (const dir of directories) { + if (!fs.existsSync(`${dir}`)) { + fs.mkdirSync(`${dir}`); + } + } +}; + +/** + * Write given JSON object to given filepath + */ +export const writeJSONToFile: (filePath: string, obj: object) => + void = (filePath: string, obj: object): void => { + fs.writeFile( + filePath, + JSON.stringify(obj, null, 2), + (err: Error) => { + if (err) { + console.error(err.message); + throw err; + } + } + ); + }; + +const extensionBinariesDir: string = __dirname + `/../../../ext/bin/`; +export const execpaths: string = `PATH="$PATH:${extensionBinariesDir}" LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${extensionBinariesDir}../lib/" `; -- cgit v1.2.1