aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/conversion/czi/czi.ts92
-rwxr-xr-xsrc/conversion/czi/cziConvert.sh2
-rw-r--r--src/conversion/czi/pyramidWorker.ts4
-rw-r--r--src/conversion/czi/tileExtraction.ts2
-rw-r--r--src/conversion/leica/requestconvertor.ts1
-rw-r--r--src/conversion/leica/scn.ts100
-rw-r--r--src/conversion/types/helpers.ts (renamed from src/conversion/types/helperCZITypes.ts)36
7 files changed, 179 insertions, 58 deletions
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<SharpInstance> = async(
- segments: Segment[][], desiredRegion: TileBounds
+ segments: Segment[][], desiredRegion: TileBounds, tmp: number
): Promise<SharpInstance> => {
// 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<void> => {
+
+ 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/helpers.ts
index 8f6310a..8e07944 100644
--- a/src/conversion/types/helperCZITypes.ts
+++ b/src/conversion/types/helpers.ts
@@ -1,3 +1,4 @@
+import * as fs from 'fs';
import { Node } from 'xml-parser';
/**
@@ -64,3 +65,38 @@ export class TileBounds {
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/" `;