From b984807d99328ff9d5813d8b9305cc92f515645e Mon Sep 17 00:00:00 2001 From: cjd24 Date: Mon, 26 Feb 2018 00:36:01 +0000 Subject: Adding script to get Jxr conversion lib, and all my current C code for extracting and converting czi files to normal things --- src/conversion/czi/convertJxrs.py | 38 +++ src/conversion/czi/czi.ts | 0 src/conversion/czi/cziConvert.sh | 10 + src/conversion/czi/cziSegmentHeaders.h | 458 +++++++++++++++++++++++++++++++++ src/conversion/czi/cziconvert.c | 354 +++++++++++++++++++++++++ 5 files changed, 860 insertions(+) create mode 100644 src/conversion/czi/convertJxrs.py create mode 100644 src/conversion/czi/czi.ts create mode 100755 src/conversion/czi/cziConvert.sh create mode 100644 src/conversion/czi/cziSegmentHeaders.h create mode 100644 src/conversion/czi/cziconvert.c (limited to 'src/conversion/czi') diff --git a/src/conversion/czi/convertJxrs.py b/src/conversion/czi/convertJxrs.py new file mode 100644 index 0000000..d19a59a --- /dev/null +++ b/src/conversion/czi/convertJxrs.py @@ -0,0 +1,38 @@ +from concurrent.futures import ThreadPoolExecutor +from subprocess import check_call +from glob import glob +from sys import argv + +totalFiles = 0 +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") + + +if __name__ == "__main__": + + if (len(argv) != 2): + print("\nMissing Argument!\n\nUsage:\npython3 convertJxrs.py ") + 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 ===========") diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/conversion/czi/cziConvert.sh b/src/conversion/czi/cziConvert.sh new file mode 100755 index 0000000..639251c --- /dev/null +++ b/src/conversion/czi/cziConvert.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +CZI_WORKING_DIR=${1:-"/cs/scratch"} +CZI_EXTRACTION_DIR=${2:-"0701-extraction"} +CZI_FILE=${3:-"2016_12_17__0701.czi"} + +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 +rm ./a.out diff --git a/src/conversion/czi/cziSegmentHeaders.h b/src/conversion/czi/cziSegmentHeaders.h new file mode 100644 index 0000000..3ed0c60 --- /dev/null +++ b/src/conversion/czi/cziSegmentHeaders.h @@ -0,0 +1,458 @@ +#include +#include + +typedef uuid_t GUID; +extern char extractDirName[100]; + + +//START FILE WRITER //////////////////////////////////////////////////////////// +void writeDataToFile(const char* filename, int fileCount, const char* optionalFileExtension, void* content, long contentSize) { + FILE* outputFile; + char outputFileName[150]; + sprintf(outputFileName, "%s%s%d%s", extractDirName, filename, fileCount, optionalFileExtension); + if ((outputFile = fopen(outputFileName, "w"))==NULL){ + printf("Write error occurred, check file path."); + exit(1); + } + fwrite(content, 1, contentSize, outputFile); + fclose(outputFile); +} +//END FILE WRITER ////////////////////////////////////////////////////////////// + + + +//START SEGMENT HEADERS///////////////////////////////////////////////////////// +typedef struct { + char name[16]; + uint64_t allocated_size; + uint64_t used_size; +} __attribute__ ((__packed__)) SegmentHeader; + +void printSegmentHeader(SegmentHeader* header) { + printf("name: %s\n", header->name); + printf("allocated_size: %" PRIu64 "\n", header->allocated_size); + printf("used_size: %" PRIu64 "\n", header->used_size); + printf("\n"); +} +void writeSegmentHeader(SegmentHeader* header, FILE* outputFile) { + fprintf(outputFile, "\"Id\": \"%s\",\n", header->name); + fprintf(outputFile, "\"AllocatedSize\": %" PRIu64 ",\n", header->allocated_size); + fprintf(outputFile, "\"UsedSize\": %" PRIu64 ",\n", header->used_size); + fprintf(outputFile, "\"Data\": \n"); +} +//END SEGMENT HEADERS/////////////////////////////////////////////////////////// + + + +//START ZISRAWFILE ///////////////////////////////////////////////////////////// +typedef struct { + uint32_t major; + uint32_t minor; + uint32_t reserved1; + uint32_t reserved2; + GUID primary_file_guid; + GUID file_guid; + uint32_t file_part; + uint64_t directory_position; + uint64_t metadata_position; + uint32_t update_pending; + uint64_t attachment_directory_potition; +} __attribute__ ((__packed__)) ZisrawFile; + +void printZisrawFile(ZisrawFile* header) { + printf("major: %" PRIu32 "\n", header->major); + printf("minor: %" PRIu32 "\n", header->minor); + printf("reserved1: %" PRIu32 "\n", header->reserved1); + printf("reserved2: %" PRIu32 "\n", header->reserved2); + printf("primary_file_guid: "); + for (int i = 0; i < 16; i++) { + printf("%u ",header->primary_file_guid[i]); + } + printf("\nfile_guid: "); + for (int i = 0; i < 16; i++) { + printf("%u ",header->file_guid[i]); + } + printf("\nfile_part: %" PRIu32 "\n", header->file_part); + printf("directory_position: %" PRIu64 "\n", header->directory_position); + printf("metadata_position: %" PRIu64 "\n", header->metadata_position); + printf("update_pending: %" PRIu32 "\n", header->update_pending); + printf("attachment_directory_potition: %" PRIu64 "\n", header->attachment_directory_potition); + printf("\n"); +} +void writeZisrawFile(ZisrawFile* header, FILE* outputFile) { + fprintf(outputFile, "{\n"); + fprintf(outputFile, "\"Major\": %" PRIu32 ",\n", header->major); + fprintf(outputFile, "\"Minor\": %" PRIu32 ",\n", header->minor); + fprintf(outputFile, "\"Reserved1\": %" PRIu32 ",\n", header->reserved1); + fprintf(outputFile, "\"Reserved2\": %" PRIu32 ",\n", header->reserved2); + fprintf(outputFile, "\"PrimaryFileGuid\": \n["); + int i = 0; + for (; i < 15; i++) { + fprintf(outputFile, "%u, ",header->primary_file_guid[i]); + } + fprintf(outputFile, "%u],\n",header->primary_file_guid[i]); + fprintf(outputFile, "\"FileGuid\": \n["); + for (i = 0; i < 15; i++) { + fprintf(outputFile, "%u, ",header->file_guid[i]); + } + fprintf(outputFile, "%u],\n",header->file_guid[i]); + fprintf(outputFile, "\"FilePart\": %" PRIu32 ",\n", header->file_part); + fprintf(outputFile, "\"DirectoryPosition\": %" PRIu64 ",\n", header->directory_position); + fprintf(outputFile, "\"MetadataPosition\": %" PRIu64 ",\n", header->metadata_position); + fprintf(outputFile, "\"UpdatePending\": %" PRIu32 ",\n", header->update_pending); + fprintf(outputFile, "\"AttachmentDirectoryPosition\": %" PRIu64 "\n", header->attachment_directory_potition); + fprintf(outputFile, "}\n"); +} +//END ZISRAWFILE /////////////////////////////////////////////////////////////// + + + +//START SubBlockDirectory///////////////////////////////////////////////////////// +typedef struct { + char dimension[4]; + int32_t start; + uint32_t size; + float start_coordinate; + uint32_t stored_size; +} __attribute__ ((__packed__)) SubBlockDimentionEntry; + +typedef struct { + char schema[2]; + uint32_t pixel_type; + uint64_t file_position; + uint32_t file_part; + uint32_t compression; + char pyramidType; + char spare1; + char spare2[4]; + uint32_t dimension_count; + SubBlockDimentionEntry* dimension_entries; +} __attribute__ ((__packed__)) SubBlockDirectoryEntry; + +typedef struct { + uint32_t entry_count; + char reserved[124]; + SubBlockDirectoryEntry* directory_entries; +} __attribute__ ((__packed__)) SubBlockDirectory; + +void printSubBlockDimentionEntry(SubBlockDimentionEntry* dimensionEntry) { + // printf(" dimension: "); + // for (int i = 0; i < 4; i++) { + // printf("%c", dimensionEntry->dimension[i]); + // } + + printf(" dimension: %s\n", dimensionEntry->dimension); + + printf(" start: %" PRIi32 "\n", dimensionEntry->start); + printf(" size: %" PRIu32 "\n", dimensionEntry->size); + printf(" start_coordinate: %f\n", dimensionEntry->start_coordinate); + printf(" stored_size: %" PRIu32 "\n", dimensionEntry->stored_size); +} +void writeSubBlockDimentionEntry(SubBlockDimentionEntry* dimensionEntry, FILE* outputFile) { + fprintf(outputFile, "{\n"); + + // fprintf(outputFile, "\"Dimension\": \""); + // for(int i = 0; i < 4; i++) { + // fprintf(outputFile, "%c", dimensionEntry->dimension[i]); + // } + // fprintf(outputFile, "\",\n\"Start\": %" PRIi32 ",\n", dimensionEntry->start); + + fprintf(outputFile, "\"Dimension\": \"%s\",\n", dimensionEntry->dimension); + fprintf(outputFile, "\"Start\": %" PRIi32 ",\n", dimensionEntry->start); + + fprintf(outputFile, "\"Size\": %" PRIu32 ",\n", dimensionEntry->size); + fprintf(outputFile, "\"StartCoordinate\": %f,\n", dimensionEntry->start_coordinate); + fprintf(outputFile, "\"StoredSize\": %" PRIu32 "\n", dimensionEntry->stored_size); + fprintf(outputFile, "}\n"); +} + +void printSubBlockDirectoryEntry(SubBlockDirectoryEntry* directoryEntry) { + printf(" schema: %c%c\n", directoryEntry->schema[0], directoryEntry->schema[1]); + printf(" pixel_type: %" PRIu32 "\n", directoryEntry->pixel_type); + printf(" file_position: %" PRIu64 "\n", directoryEntry->file_position); + printf(" file_part: %" PRIu32 "\n", directoryEntry->file_part); + printf(" compression: %" PRIu32 "\n", directoryEntry->compression); + printf(" pyramidType: %u\n", directoryEntry->pyramidType); + printf(" spare1: %d\n", directoryEntry->spare1); + printf(" spare2: %d %d %d %d\n", directoryEntry->spare2[0], directoryEntry->spare2[1], directoryEntry->spare2[2], directoryEntry->spare2[3]); + printf(" dimension_count: %" PRIu32 "\n", directoryEntry->dimension_count); + printf(" dimension_entries: \n"); + for (uint32_t i = 0; i < directoryEntry->dimension_count; i++) { + printSubBlockDimentionEntry(&directoryEntry->dimension_entries[i]); + } + printf("\n"); +} +void writeSubBlockDirectoryEntry(SubBlockDirectoryEntry* directoryEntry, FILE* outputFile) { + fprintf(outputFile, "{\n"); + fprintf(outputFile, "\"SchemaType\": \"%c%c\",\n", directoryEntry->schema[0],directoryEntry->schema[1]); + fprintf(outputFile, "\"PixelType\": %" PRIu32 ",\n", directoryEntry->pixel_type); + fprintf(outputFile, "\"FilePosition\": %" PRIu64 ",\n", directoryEntry->file_position); + fprintf(outputFile, "\"FilePart\": %" PRIu32 ",\n", directoryEntry->file_part); + fprintf(outputFile, "\"Compression\": %" PRIu32 ",\n", directoryEntry->compression); + fprintf(outputFile, "\"PyramidType\": \"%u\",\n", directoryEntry->pyramidType); + fprintf(outputFile, "\"spare1\": %d,\n", directoryEntry->spare1); + fprintf(outputFile, "\"spare2\": \"%d %d %d %d\",\n", directoryEntry->spare2[0], directoryEntry->spare2[1], directoryEntry->spare2[2], directoryEntry->spare2[3]); + fprintf(outputFile, "\"DimensionCount\": %" PRIu32 ",\n", directoryEntry->dimension_count); + fprintf(outputFile, "\"DimensionEntries\": \n[\n"); + uint32_t i = 0; + for (; i < directoryEntry->dimension_count - 1; i++) { + writeSubBlockDimentionEntry(&directoryEntry->dimension_entries[i], outputFile); + fprintf(outputFile, ", "); + } + writeSubBlockDimentionEntry(&directoryEntry->dimension_entries[i], outputFile); + fprintf(outputFile, "]}\n"); +} + +void printSubBlockDirectory(SubBlockDirectory* zisDirectory) { + printf("entry_count: %" PRIu32 "\n", zisDirectory->entry_count); + printf("reserved: %s\n", zisDirectory->reserved); + printf("directory_entries: \n"); + for (uint32_t i = 0; i < zisDirectory->entry_count; i++) { + printSubBlockDirectoryEntry(&zisDirectory->directory_entries[i]); + } +} +void writeSubBlockDirectory(SubBlockDirectory* zisDirectory, FILE* outputFile) { + fprintf(outputFile, "{\n"); + fprintf(outputFile, "\"EntryCount\": %" PRIu32 ",\n", zisDirectory->entry_count); + fprintf(outputFile, "\"Reserved\": \"%s\",\n", zisDirectory->reserved); + fprintf(outputFile, "\"Entry\": \n[\n"); + uint32_t i = 0; + for (; i < zisDirectory->entry_count - 1; i++) { + writeSubBlockDirectoryEntry(&zisDirectory->directory_entries[i], outputFile); + fprintf(outputFile, ", "); + } + writeSubBlockDirectoryEntry(&zisDirectory->directory_entries[i], outputFile); + fprintf(outputFile, "]}\n"); +} +//END SubBlockDirectory/////////////////////////////////////////////////////////// + + + +//START METADATASEGMENT///////////////////////////////////////////////////////// +typedef struct { + uint32_t xml_size; + uint32_t attachment_size; + char spare[248]; +} __attribute__ ((__packed__)) MetadataSegment; + +void printMetadataSegment(MetadataSegment* metaSegement) { + printf("xml_size: %" PRIu32 "\n", metaSegement->xml_size); + printf("attachment_size: %" PRIu32 "\n", metaSegement->attachment_size); + printf("spare: \n"); + printf("Document Name: %s", "FILE-META-1.xml"); +} +void writeMetadataSegment(MetadataSegment* metaSegement, FILE* outputFile) { + fprintf(outputFile, "{\n"); + fprintf(outputFile, "\"XmlSize\": %" PRIu32 ",\n", metaSegement->xml_size); + fprintf(outputFile, "\"AttachmentSize\": %" PRIu32 ",\n", metaSegement->attachment_size); + fprintf(outputFile, "\"\": \"<256-8>\",\n"); + fprintf(outputFile, "\"XmlName\": \"FILE-META-1.xml\"\n"); + fprintf(outputFile, "}\n"); +} +//END METADATASEGMENT/////////////////////////////////////////////////////////// + + + +//START SUBBLOCKSEGMENT///////////////////////////////////////////////////////// +typedef struct { + uint32_t metadata_size; + uint32_t attachment_size; + uint64_t data_size; + SubBlockDirectoryEntry directory_entry; + char* metadata; + void* data; + void* attachments; +} __attribute__ ((__packed__)) SubBlockSegment; + +void printSubBlockSegment(SubBlockSegment* subBlockSegment) { + static int META_COUNT = 0; + static int DATA_COUNT = 0; + static int ATTACH_COUNT = 0; + printf("metadata_size: %" PRIu32 "\n", subBlockSegment->metadata_size); + printf("attachment_size: %" PRIu32 "\n", subBlockSegment->attachment_size); + printf("data_size: %" PRIu64 "\n", subBlockSegment->data_size); + printf("spare: \n"); + printSubBlockDirectoryEntry(&subBlockSegment->directory_entry); + if (strncmp(subBlockSegment->metadata, "", subBlockSegment->metadata_size) != 0) { + printf("metadata: \"metadata-%d\"\n", META_COUNT++); + } else { + printf("metadata: \"empty\"\n"); + } + printf("data: \"data-%d\"\n", DATA_COUNT++); + if (subBlockSegment->attachment_size != 0) { + printf("attatchments: \"attach-%d\"\n", ATTACH_COUNT++); + } else { + printf("attatchments: \"empty\"\n"); + } +} + +int findEqualDimension(SubBlockDirectoryEntry* directoryEntry, const char* dimensionName) { + + for (uint32_t i = 0; i < directoryEntry->dimension_count; i++) { + if (strcmp(directoryEntry->dimension_entries[i].dimension, dimensionName) == 0) { + if (directoryEntry->dimension_entries[i].size == directoryEntry->dimension_entries[i].stored_size) { + return 1; + } else { + return 0; + } + } + } + return 0; +} + +void writeSubBlockSegment(SubBlockSegment* subBlockSegment, FILE* outputFile) { + + static int META_COUNT = 0; + static int DATA_COUNT = 0; + static int ATTACH_COUNT = 0; + + fprintf(outputFile, "{\n"); + fprintf(outputFile, "\"MetadataSize\": %" PRIu32 ",\n", subBlockSegment->metadata_size); + fprintf(outputFile, "\"AttachmentSize\": %" PRIu32 ",\n", subBlockSegment->attachment_size); + fprintf(outputFile, "\"DataSize\": %" PRIu64 ",\n", subBlockSegment->data_size); + fprintf(outputFile, "\"DirectoryEntry\": "); + writeSubBlockDirectoryEntry(&subBlockSegment->directory_entry, outputFile); + fprintf(outputFile, ",\n\"Fill\": \"\",\n"); + + /* open file for Output */ + if (strncmp(subBlockSegment->metadata, "", subBlockSegment->metadata_size) != 0) { + writeDataToFile("metadata-", META_COUNT, ".xml", subBlockSegment->metadata, subBlockSegment->metadata_size); + fprintf(outputFile, "\"Metadata\": \"metadata-%d.xml\",\n", META_COUNT++); + } else { + fprintf(outputFile, "\"Metadata\": \"empty\",\n"); + } + + if (findEqualDimension(&subBlockSegment->directory_entry, "X") && findEqualDimension(&subBlockSegment->directory_entry, "Y")) { + writeDataToFile("data-", DATA_COUNT, ".jxr", subBlockSegment->data, subBlockSegment->data_size); + fprintf(outputFile, "\"Data\": \"data-%d.png\",\n", DATA_COUNT++); + } else { + fprintf(outputFile, "\"Data\": \"empty\",\n"); + } + + if (subBlockSegment->attachment_size != 0) { + writeDataToFile("attach-", ATTACH_COUNT, "", subBlockSegment->attachments, subBlockSegment->attachment_size); + fprintf(outputFile, "\"Attachments\": \"attach-%d\"\n", ATTACH_COUNT++); + } else { + fprintf(outputFile, "\"Attachments\": \"empty\"\n"); + } + fprintf(outputFile, "}\n"); +} +//END SUBBLOCKSEGMENT/////////////////////////////////////////////////////////// + + + + + + + +//START ATTACHMENTENTRY///////////////////////////////////////////////////////// +typedef struct { + char schema_type[2]; + char reserved[10]; + uint64_t file_position; + int file_part; + GUID content_guid; + char content_file_type[8]; + char name[80]; +} __attribute__ ((__packed__)) AttachmentEntry; + +void printAttachmentEntry(AttachmentEntry* attachmentSegment){ + printf(" schema_type: \"%c%c\"\n", attachmentSegment->schema_type[0],attachmentSegment->schema_type[1]); + printf(" reserved: %s\n", attachmentSegment->reserved); + printf(" file_position: %" PRIu64 "\n", attachmentSegment->file_position); + printf(" file_part: %d\n", attachmentSegment->file_part); + printf(" ContentGuid: ["); + int i = 0; + for (; i < 15; i++) { + printf("%u, ", attachmentSegment->content_guid[i]); + } + printf("%u]\n", attachmentSegment->content_guid[i]); + printf(" content_file_type: \"%s\"\n", attachmentSegment->content_file_type); + printf(" name: \"%s\"\n", attachmentSegment->name); +} +void writeAttachmentEntry(AttachmentEntry* attachmentSegment, FILE* outputFile){ + fprintf(outputFile, "{\n"); + fprintf(outputFile, "\"SchemaType\": \"%c%c\",\n", attachmentSegment->schema_type[0],attachmentSegment->schema_type[1]); + fprintf(outputFile, "\"Reserved\": \"%s\",\n", attachmentSegment->reserved); + fprintf(outputFile, "\"FilePosition\": %" PRIu64 ",\n", attachmentSegment->file_position); + fprintf(outputFile, "\"FilePart\": %d,\n", attachmentSegment->file_part); + fprintf(outputFile, "\"ContentGuid\": \n["); + int i = 0; + for (; i < 15; i++) { + fprintf(outputFile, "%u, ", attachmentSegment->content_guid[i]); + } + fprintf(outputFile, "%u],\n", attachmentSegment->content_guid[i]); + fprintf(outputFile, "\"ContentFileType\": \"%s\",\n", attachmentSegment->content_file_type); + fprintf(outputFile, "\"Name\": \"%s\"\n", attachmentSegment->name); + fprintf(outputFile, "}\n"); +} + +//END ATTACHMENTENTRY/////////////////////////////////////////////////////////// + + + + + + +//START ATTACHMENTSEGMENT/////////////////////////////////////////////////////// +typedef struct { + uint32_t data_size; + char spare1[12]; + AttachmentEntry attachment_entry; + char spare2[112]; + void* data; +} __attribute__ ((__packed__)) AttachmentSegment; + +void printAttachmentSegment(AttachmentSegment* attachmentSegment){ + + static int ATTACH_DATA_COUNT = 0; + + printf("data_size: %" PRIu32 "\n", attachmentSegment->data_size); + printAttachmentEntry(&attachmentSegment->attachment_entry); + printf("data: \"attach-data-%d\"\n", ATTACH_DATA_COUNT++); +} +void writeAttachmentSegment(AttachmentSegment* attachmentSegment, FILE* outputFile){ + + static int ATTACH_DATA_COUNT = 0; + + fprintf(outputFile, "{\n"); + fprintf(outputFile, "\"DataSize\": %" PRIu32 ",\n", attachmentSegment->data_size); + fprintf(outputFile, "\"AttachmentEntry\": "); + writeAttachmentEntry(&attachmentSegment->attachment_entry, outputFile); + + /* open file for Output */ + writeDataToFile("attach-data-", ATTACH_DATA_COUNT, "", attachmentSegment->data, attachmentSegment->data_size); + + fprintf(outputFile, ",\n\"Data\": \"attach-data-%d\"\n", ATTACH_DATA_COUNT++); + fprintf(outputFile, "}\n"); +} +//END ATTACHMENTSEGMENT///////////////////////////////////////////////////////// + + + +//END ATTACHMENTDIRECTORY/////////////////////////////////////////////////////// +typedef struct { + int entry_count; + char reserved[252]; + AttachmentEntry* attachment_entries; +} __attribute__ ((__packed__)) AttachmentDirectory; + +void printAttachmentDirectory(AttachmentDirectory* attachmentDirectory){ + printf("entry_count: %d\n", attachmentDirectory->entry_count); + for (int i = 0; i < attachmentDirectory->entry_count; i++) { + printAttachmentEntry(&attachmentDirectory->attachment_entries[i]); + } +} +void writeAttachmentDirectory(AttachmentDirectory* attachmentDirectory, FILE* outputFile){ + fprintf(outputFile, "{\n"); + fprintf(outputFile, "\"EntryCount\": %d,\n", attachmentDirectory->entry_count); + fprintf(outputFile, "\"Entry\": [\n"); + int i = 0; + for (; i < attachmentDirectory->entry_count - 1; i++) { + writeAttachmentEntry(&attachmentDirectory->attachment_entries[i], outputFile); + fprintf(outputFile, ", "); + } + writeAttachmentEntry(&attachmentDirectory->attachment_entries[i], outputFile); + fprintf(outputFile, "]}\n"); +} +//END ATTACHMENTDIRECTORY/////////////////////////////////////////////////////// diff --git a/src/conversion/czi/cziconvert.c b/src/conversion/czi/cziconvert.c new file mode 100644 index 0000000..85b925c --- /dev/null +++ b/src/conversion/czi/cziconvert.c @@ -0,0 +1,354 @@ +#include +#include +#include + +#include "cziSegmentHeaders.h" + +void writeDataToFile(const char* filename, int fileCount, const char* optionalFileExtension, void* content, long contentSize); +char extractDirName[100]; +long totalFileSize; +long lastPercentFileProgress = -1; +SegmentHeader* segHead; +SubBlockDirectory* zisDirectory; +SubBlockSegment* zisSubBlock; +AttachmentSegment* attachmentSegment; +AttachmentDirectory* attachmentDirectory; +MetadataSegment* metadataSegment; + + + +void setFileOffset(FILE* streamPointer, long currentPosition, SegmentHeader* segment) { + // if (segment->used_size == 0) { + fseek(streamPointer, currentPosition + segment->allocated_size, SEEK_SET); + // } else { + // fseek(streamPointer, currentPosition + segment->used_size, SEEK_SET); + // } +} + +int findSegmentID() { + + if (strcmp(segHead->name, "ZISRAWSUBBLOCK") == 0) { + return 3; + } + else if (strcmp(segHead->name, "ZISRAWATTACH") == 0) { + return 5; + } + else if (strcmp(segHead->name, "ZISRAWATTDIR") == 0) { + return 6; + } + else if (strcmp(segHead->name, "ZISRAWDIRECTORY") == 0) { + return 2; + } + else if (strcmp(segHead->name, "DELETED") == 0) { + return 7; + } + else if (strcmp(segHead->name, "ZISRAWMETADATA") == 0) { + return 4; + } + else if (strcmp(segHead->name, "ZISRAWFILE") == 0) { + return 1; + } + else { + return -1; + } +} + + +void loadMainHeader(FILE* imageFile, FILE* outputFile, long* fileOffset) { + + //initial thing. + fprintf(outputFile,"{\n"); + writeSegmentHeader(segHead, outputFile); + + //main file descriptor + ZisrawFile* zisFileHeader = malloc(sizeof(ZisrawFile)); + fread(zisFileHeader, sizeof(ZisrawFile), 1, imageFile); + + //print and write to file +// printZisrawFile(zisFileHeader); + writeZisrawFile(zisFileHeader, outputFile); + free(zisFileHeader); + fprintf(outputFile,"}\n"); + + //correct for Zero Paddings + setFileOffset(imageFile, *fileOffset, segHead); +} + + +void loadZisDirectories(SubBlockDirectory* zisrawDirectory, FILE* imageFile) { + + //Get the main directory; + fread(zisrawDirectory, sizeof(SubBlockDirectory), 1, imageFile); + //Take care for the fact that what we are using as a pointer value in struct size is actually just the first address. + fseek(imageFile, -8, SEEK_CUR); + //allocate space for each of the directory entries + zisrawDirectory->directory_entries = malloc(sizeof(SubBlockDirectoryEntry) * zisrawDirectory->entry_count); + + //now get each Directory entry + for (uint32_t i = 0; i < zisrawDirectory->entry_count; i++) { + + //read in the directory entry + fread(&zisrawDirectory->directory_entries[i], sizeof(SubBlockDirectoryEntry), 1, imageFile); + //Again cater for the struct pointer size difference + fseek(imageFile, -8, SEEK_CUR); + + //malloc the dimension entry requirements into the above directory entries pointer + zisrawDirectory->directory_entries[i].dimension_entries = malloc(sizeof(SubBlockDimentionEntry) * zisrawDirectory->directory_entries[i].dimension_count); + + //read in the dimension entries into the new malloc location + fread(zisrawDirectory->directory_entries[i].dimension_entries, sizeof(SubBlockDimentionEntry), zisrawDirectory->directory_entries[i].dimension_count, imageFile); + } +} +void freeZisDirectories(SubBlockDirectory* zisrawDirectory) { + //now get each Directory entry + for (uint32_t i = 0; i < zisrawDirectory->entry_count; i++) { + //free the dimension entry requirements into the above directory entries pointer + free(zisrawDirectory->directory_entries[i].dimension_entries); + } + //free space for each of the directory entries + free(zisrawDirectory->directory_entries); +} + + +void loadSubBlockSegment(SubBlockSegment* subBlockSegment, FILE* imageFile) { + + long offsetCorrection = ftell(imageFile); + //Get the fixed size content; + fread(subBlockSegment, sizeof(SubBlockDirectoryEntry) + 8, 1, imageFile); + //read in the directoryEntry + subBlockSegment->directory_entry.dimension_entries = malloc(subBlockSegment->directory_entry.dimension_count * sizeof(SubBlockDimentionEntry)); + //read in the dimensions + fread(subBlockSegment->directory_entry.dimension_entries, sizeof(SubBlockDimentionEntry), subBlockSegment->directory_entry.dimension_count, imageFile); + + //Deal with the "fill" block + offsetCorrection = ftell(imageFile) - offsetCorrection; + offsetCorrection = 256 - offsetCorrection; + if (offsetCorrection > 0) { + fseek(imageFile, offsetCorrection, SEEK_CUR); + } + + // metadata block + subBlockSegment->metadata = malloc(subBlockSegment->metadata_size); + fread(subBlockSegment->metadata, 1, subBlockSegment->metadata_size, imageFile); + + // data block + subBlockSegment->data = malloc(subBlockSegment->data_size); + fread(subBlockSegment->data, 1, subBlockSegment->data_size, imageFile); + + // attach block + subBlockSegment->attachments = malloc(subBlockSegment->attachment_size); + fread(subBlockSegment->attachments, 1, subBlockSegment->attachment_size, imageFile); +} +void freeSubBlockSegment(SubBlockSegment* subBlockSegment) { + //free the directoryEntry + free(subBlockSegment->directory_entry.dimension_entries); + + // metadata block + free(subBlockSegment->metadata); + + // data block + free(subBlockSegment->data); + + // attach block + free(subBlockSegment->attachments); +} + + +void loadAttachmentSegment(AttachmentSegment* attachmentSegment, FILE* imageFile) { + + //Get the fixed size content; + fread(attachmentSegment, sizeof(AttachmentSegment), 1, imageFile); + //account for the pointer space + fseek(imageFile, -8, SEEK_CUR); + + //make space for the data element; + attachmentSegment->data = malloc(attachmentSegment->data_size); + + //read in the data + fread(attachmentSegment->data, attachmentSegment->data_size, 1, imageFile); +} +void freeAttachmentSegment(AttachmentSegment* attachmentSegment) { + //free the data area + free(attachmentSegment->data); +} + + +void loadAttachmentDirectory(AttachmentDirectory* attachmentDirectory, FILE* imageFile) { + + //Get the fixed size content; + fread(attachmentDirectory, sizeof(AttachmentDirectory), 1, imageFile); + //account for the pointer space + fseek(imageFile, -8, SEEK_CUR); + //malloc the space for the attachments; + attachmentDirectory->attachment_entries = malloc(sizeof(AttachmentEntry) * attachmentDirectory->entry_count); + //read in the content; + fread(attachmentDirectory->attachment_entries, sizeof(AttachmentEntry), attachmentDirectory->entry_count, imageFile); +} +void freeAttachmentDirectory(AttachmentDirectory* attachmentDirectory) { + //free the entries area + free(attachmentDirectory->attachment_entries); +} + +void loadMetadataSegment(MetadataSegment* metadataSegment, FILE* imageFile) { + fread(metadataSegment, sizeof(MetadataSegment), 1, imageFile); +} +void loadAndWriteMetadataData(MetadataSegment* metadataSegment, FILE* imageFile) { + void* rawMetadata = malloc(metadataSegment->xml_size); + fread(rawMetadata, 1, metadataSegment->xml_size, imageFile); + writeDataToFile("FILE-META-", 1, ".xml", rawMetadata, metadataSegment->xml_size); + free(rawMetadata); +} + + +int functionRouter(FILE* imageFile, FILE* jsonOutput, long* fileOffset) { + + //next segment header + long newPercent = (100 * ftell(imageFile) / totalFileSize); + if (newPercent > lastPercentFileProgress) { + lastPercentFileProgress = newPercent; + printf("> Amount of CZI file extracted: %3ld%%\n", lastPercentFileProgress); + } + + if (fread(segHead, sizeof(SegmentHeader), 1, imageFile) != 1) { + return 0; + } + *fileOffset = ftell(imageFile); + + //"prettify + print lol" +// printSegmentHeader(segHead); + fprintf(jsonOutput,"{\n"); + writeSegmentHeader(segHead, jsonOutput); + + //deal with the specific kind of segement. + switch (findSegmentID()) { + + //FileTitle + case 1: + loadMainHeader(imageFile, jsonOutput, fileOffset); + break; + + //Directory + case 2: + loadZisDirectories(zisDirectory, imageFile); + writeSubBlockDirectory(zisDirectory, jsonOutput); + freeZisDirectories(zisDirectory); + break; + + //Subblock + case 3: + loadSubBlockSegment(zisSubBlock, imageFile); +// printSubBlockSegment(zisSubBlock); + writeSubBlockSegment(zisSubBlock, jsonOutput); + freeSubBlockSegment(zisSubBlock); + break; + + //MetaData + case 4: + loadMetadataSegment(metadataSegment, imageFile); +// printMetadataSegment(metadataSegment); + writeMetadataSegment(metadataSegment, jsonOutput); + loadAndWriteMetadataData(metadataSegment, imageFile); + break; + + //Attseg + case 5: + loadAttachmentSegment(attachmentSegment, imageFile); +// printAttachmentSegment(attachmentSegment); + writeAttachmentSegment(attachmentSegment, jsonOutput); + freeAttachmentSegment(attachmentSegment); + break; + + //Attdir + case 6: + loadAttachmentDirectory(attachmentDirectory, imageFile); +// printAttachmentDirectory(attachmentDirectory); + writeAttachmentDirectory(attachmentDirectory, jsonOutput); + freeAttachmentDirectory(attachmentDirectory); + break; + + //DELETED + case 7: + fprintf(jsonOutput, "{}"); + break; + + default: + fprintf(stderr, "FAILED TO PARSE SEGMENT HEADER: %s", segHead->name); + exit(1); + } + + setFileOffset(imageFile, *fileOffset, segHead); + fprintf(jsonOutput,"},\n"); + return 1; +} + +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 \n\n"); + exit(1); + } + + //create file objects; + FILE* imageFile; + FILE* jsonOutput; + long fileOffset = 0; + strcpy(extractDirName, argv[2]); + + /* open file for input */ + if ((imageFile = fopen(argv[1], "r"))==NULL){ + printf("Read error occurred, check file path."); + exit(1); + } + fseek(imageFile, 0, SEEK_END); + totalFileSize = ftell(imageFile); + fseek(imageFile, 0, SEEK_SET); + + /* open file for Output */ + char jsonName[90]; + strcpy(jsonName, extractDirName); + strcat(jsonName, "outputjson.json"); + if ((jsonOutput = fopen(jsonName, "w"))==NULL){ + printf("Write error occurred, check file path."); + exit(1); + } + fprintf(jsonOutput,"{ \"czi\": [\n"); + + + //create heap space for a header and directory stuff. + segHead = malloc(sizeof(SegmentHeader)); + zisDirectory = malloc(sizeof(SubBlockDirectory)); + zisSubBlock = malloc(sizeof(SubBlockSegment)); + attachmentSegment = malloc(sizeof(AttachmentSegment)); + attachmentDirectory = malloc(sizeof(AttachmentDirectory)); + metadataSegment = malloc(sizeof(MetadataSegment)); + + + printf("\n=========== BEGIN CZI EXTRACTION ===========\n\n"); + while (functionRouter(imageFile, jsonOutput, &fileOffset)); + //get rid of the last comma + fseek(jsonOutput, -2, SEEK_CUR); + //close stuff + free(segHead); + free(zisDirectory); + free(zisSubBlock); + free(attachmentSegment); + free(attachmentDirectory); + free(metadataSegment); + fclose(imageFile); + fprintf(jsonOutput,"\n]}\n"); + 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; +} -- cgit v1.2.1 From 2a5095da5c568b6b63d4e438f3d83320300e3435 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Sun, 4 Mar 2018 18:13:47 +0000 Subject: Playing around trying to get a list of base tiles we may be interested in for building pyramid --- src/conversion/czi/czi.ts | 114 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) (limited to 'src/conversion/czi') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index e69de29..7d7af1d 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -0,0 +1,114 @@ +var json = require('/cs/scratch/cjd24/0701-extraction/outputjson.json'); +json = json.czi; +let tileOverlap = 5; +let tileSize = 1024; + +var dataBlocks = json.filter((x: { Id: string, Data: { Data: string }}) => x.Id == 'ZISRAWSUBBLOCK' && x.Data.Data != 'empty'); + +var filterX = dataBlocks.map((x: {Data: {DirectoryEntry: {DimensionEntries: {Start: number}[]}}}) => x.Data.DirectoryEntry.DimensionEntries[0].Start); +var filterY = dataBlocks.map((x: {Data: {DirectoryEntry: {DimensionEntries: {Start: number}[]}}}) => x.Data.DirectoryEntry.DimensionEntries[1].Start); + +var uniqueX = filterX.filter(function(elem: any, pos: any) { + return filterX.indexOf(elem) == pos; +}) + +var uniqueY = filterY.filter(function(elem: any, pos: any) { + return filterY.indexOf(elem) == pos; +}) + + +//These values are normally stored at the big XML metadata under "Information/Image/SizeX or SizeY"; +var sizeX = 0; +var sizeY = 0; +for (var i = 0; i < uniqueX.length; i++) { + sizeX += dataBlocks[i].Data.DirectoryEntry.DimensionEntries[0].Size; +} +for (var i = 0; i < uniqueY.length; i++) { + sizeY += dataBlocks[i * uniqueX.length].Data.DirectoryEntry.DimensionEntries[1].Size; +} + + +console.log("\n\nSizeX : " + sizeX); +console.log("UNIQUE X VALUES:"); +console.log(uniqueX); +console.log("\n\nSizeY : " + sizeY); +console.log("UNIQUE Y VALUES:"); +console.log(uniqueY); +console.log("\n\n\n\n\n\n"); + + +console.log(findRelatedTiles(0, 0)); + + + + + + + + + + + + + + +function getOriginalTileCoordinates(originalTile: any): number[] | null{ + let xstart:number | null = null, + xsize:number | null = null, + ystart:number | null = null, + ysize:number | null = null; + + for (let dimension of originalTile.Data.DirectoryEntry) { + if (dimension.Dimension == 'X') { + xstart = dimension.Start; + xsize = dimension.Size; + continue; + } + if (dimension.Dimension == 'Y') { + ystart = dimension.Start; + ysize = dimension.Size; + continue; + } + } + + if (!xstart || !xsize || !ystart || !ysize) { + return null; + } else { + return [xstart, xsize, ystart, ysize]; + } +} + + +function findRelatedTiles(desiredX: number, desiredY: number): any[] { + let relatedTiles: any[] = []; + + for (let origTile in dataBlocks) { + let origCoords: number[] | null = getOriginalTileCoordinates(origTile); + if (origCoords === null) { + return ["There was a sad boi error"]; + } + + //desired X on left is within current tile + if ((((desiredX - tileOverlap) > origCoords[0]) && + ((desiredX - tileOverlap) < (origCoords[0] + origCoords[1]))) || + + //desired X on right is within the current tile + (((desiredX + tileSize + tileOverlap) > origCoords[0]) && + ((desiredX + tileSize + tileOverlap) < (origCoords[0] + origCoords[1])))) { + + + //desired Y on top is within current tile + if ((((desiredY - tileOverlap) > origCoords[2]) && + ((desiredY - tileOverlap) < (origCoords[2] + origCoords[3]))) || + + //desired Y on bottom is within the current tile + (((desiredY + tileSize + tileOverlap) > origCoords[2]) && + ((desiredY + tileSize + tileOverlap) < (origCoords[2] + origCoords[3])))) { + + relatedTiles.push(origTile); + } + } + } + + return relatedTiles; +} -- cgit v1.2.1 From 694b0bc100171c443e6abd053ad20110a01c2a91 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Mon, 5 Mar 2018 19:44:09 +0000 Subject: Made the initial dabble into CZI tile builder type-scriptified --- src/conversion/czi/czi.ts | 274 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 202 insertions(+), 72 deletions(-) (limited to 'src/conversion/czi') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 7d7af1d..720d711 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -1,114 +1,244 @@ -var json = require('/cs/scratch/cjd24/0701-extraction/outputjson.json'); +let json: any = require('/cs/scratch/cjd24/0701-extraction/outputjson.json'); json = json.czi; -let tileOverlap = 5; -let tileSize = 1024; -var dataBlocks = json.filter((x: { Id: string, Data: { Data: string }}) => x.Id == 'ZISRAWSUBBLOCK' && x.Data.Data != 'empty'); +let tileOverlap: number = 5; +let tileSize: number = 1024; -var filterX = dataBlocks.map((x: {Data: {DirectoryEntry: {DimensionEntries: {Start: number}[]}}}) => x.Data.DirectoryEntry.DimensionEntries[0].Start); -var filterY = dataBlocks.map((x: {Data: {DirectoryEntry: {DimensionEntries: {Start: number}[]}}}) => x.Data.DirectoryEntry.DimensionEntries[1].Start); - -var uniqueX = filterX.filter(function(elem: any, pos: any) { - return filterX.indexOf(elem) == pos; -}) - -var uniqueY = filterY.filter(function(elem: any, pos: any) { - return filterY.indexOf(elem) == pos; -}) - - -//These values are normally stored at the big XML metadata under "Information/Image/SizeX or SizeY"; -var sizeX = 0; -var sizeY = 0; -for (var i = 0; i < uniqueX.length; i++) { - sizeX += dataBlocks[i].Data.DirectoryEntry.DimensionEntries[0].Size; +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; } -for (var i = 0; i < uniqueY.length; i++) { - sizeY += dataBlocks[i * uniqueX.length].Data.DirectoryEntry.DimensionEntries[1].Size; +class TileBounds { + left: number; + right: number; + top: number; + bottom: number; + constructor(left: number, right: number, top: number, bottom: number) { + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + }; } -console.log("\n\nSizeX : " + sizeX); -console.log("UNIQUE X VALUES:"); -console.log(uniqueX); -console.log("\n\nSizeY : " + sizeY); -console.log("UNIQUE Y VALUES:"); -console.log(uniqueY); -console.log("\n\n\n\n\n\n"); +//Get all subblocks that have an associated saved tile +let dataBlocks: Segment[] = json.filter((x: Segment) => x.Id == 'ZISRAWSUBBLOCK' && x.Data.Data != 'empty'); -console.log(findRelatedTiles(0, 0)); +function getOriginalTileBounds(originalTile: Segment): TileBounds | null { + let bounds: TileBounds = new TileBounds (-1, -1, -1, -1); + for (let dimension of originalTile.Data.DirectoryEntry.DimensionEntries) { + if (dimension.Dimension == 'X') { + bounds.left = dimension.Start; + bounds.right = bounds.left + dimension.Size; + continue; + } + else if (dimension.Dimension == 'Y') { + bounds.top = dimension.Start; + bounds.bottom = bounds.top + dimension.Size; + continue; + } + } + if (bounds.left < 0 || bounds.right < 0 || bounds.top < 0 || bounds.bottom < 0) { + return null; + } + return bounds; +} +function findRelatedTiles(activeSegments: Segment[], desiredX: number, desiredY: number): Segment[] { + let relatedTiles: Segment[] = []; + for (let origTile of activeSegments) { + let origCoords: TileBounds | null; + if ((origCoords = getOriginalTileBounds(origTile)) === null) { + throw new Error("There was a Sad Boi error"); + } + let desired = new TileBounds( + desiredX - tileOverlap, + desiredX + tileSize + tileOverlap, + desiredY - tileOverlap, + desiredY + tileSize + tileOverlap + ); + //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))) -function getOriginalTileCoordinates(originalTile: any): number[] | null{ - let xstart:number | null = null, - xsize:number | null = null, - ystart:number | null = null, - ysize:number | null = null; + { + //desired Y on top is within current tile + if (((desired.top >= origCoords.top) && + (desired.top <= origCoords.bottom)) || - for (let dimension of originalTile.Data.DirectoryEntry) { - if (dimension.Dimension == 'X') { - xstart = dimension.Start; - xsize = dimension.Size; - continue; - } - if (dimension.Dimension == 'Y') { - ystart = dimension.Start; - ysize = dimension.Size; - continue; + //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(origTile); + } } } - if (!xstart || !xsize || !ystart || !ysize) { - return null; - } else { - return [xstart, xsize, ystart, ysize]; + return relatedTiles; +} + + +function getDimension(segment:Segment, name:string): Dimension | null { + for (let dimension of segment.Data.DirectoryEntry.DimensionEntries) { + if (dimension.Dimension == name) { + return dimension; + } } + return null; } -function findRelatedTiles(desiredX: number, desiredY: number): any[] { - let relatedTiles: any[] = []; - for (let origTile in dataBlocks) { - let origCoords: number[] | null = getOriginalTileCoordinates(origTile); - if (origCoords === null) { - return ["There was a sad boi error"]; - } - //desired X on left is within current tile - if ((((desiredX - tileOverlap) > origCoords[0]) && - ((desiredX - tileOverlap) < (origCoords[0] + origCoords[1]))) || - //desired X on right is within the current tile - (((desiredX + tileSize + tileOverlap) > origCoords[0]) && - ((desiredX + tileSize + tileOverlap) < (origCoords[0] + origCoords[1])))) { - //desired Y on top is within current tile - if ((((desiredY - tileOverlap) > origCoords[2]) && - ((desiredY - tileOverlap) < (origCoords[2] + origCoords[3]))) || - //desired Y on bottom is within the current tile - (((desiredY + tileSize + tileOverlap) > origCoords[2]) && - ((desiredY + tileSize + tileOverlap) < (origCoords[2] + origCoords[3])))) { - relatedTiles.push(origTile); - } + + +//Get all values of X and Y respectively. +let filterX: number[] = dataBlocks.map((x: Segment) => + { + let y: Dimension | null = getDimension(x, 'X'); + return y == null ? -1 : y.Start + }); +let filterY: number[] = dataBlocks.map((x: Segment) => + { + let y: Dimension | null = getDimension(x, 'Y'); + return y == null ? -1 : y.Start + }); + + +//Filter all values to only keep the unique ones for X and Y coords respectively. +let uniqueX: number[] = filterX.filter(function(elem: any, pos: any) { + return filterX.indexOf(elem) == pos; +}); +let uniqueY: number[] = filterY.filter(function(elem: any, pos: any) { + return filterY.indexOf(elem) == pos; +}); + +/*These values are normally stored at the big XML metadata under "Information/Image/SizeX or SizeY"; +However for the sake of hacking around, assume that the tiles in memory are +going from left to right; top to bottom. like a book, then use this in order +to count up the total size (in pixels) of the image*/ +let sizeX: number = 0; +let sizeY: number = 0; +for (let i: number = 0; i < uniqueX.length; i++) { + let temp : Dimension | null = getDimension(dataBlocks[i], 'X'); + if (temp != null) { + sizeX += temp.Size; + } +}; +for (let i: number = 0; i < uniqueY.length; i++) { + let temp : Dimension | null = getDimension(dataBlocks[i * uniqueX.length], 'Y'); + if (temp != null) + sizeY += temp.Size; +}; +tileOverlap + +let uniqueTileSizes: number[][] = []; +for (let seg of dataBlocks) { + let newx = getDimension(seg, 'X'), newy = getDimension(seg, 'Y'); + if (newx == null || newy == null) {continue;}; + let x: number = newx.Size, y: number = newy.Size; + let found: boolean = false; + for (let dimPair of uniqueTileSizes) { + if (x == dimPair[0] && y == dimPair[1]) { + found = true; + break; } } + if (!found) { + uniqueTileSizes.push([x, y]); + } +}; - return relatedTiles; + + + + + +//TESTS TO SEE WHAT VARIOUS THINGS RETURN +// `npm bin`/ts-node czi.ts +console.log("\n\nUnique Tile Sizes:"); +console.log(uniqueTileSizes); +console.log("\n\nSizeX : " + sizeX); +console.log("UNIQUE X VALUES:"); +console.log("[" + uniqueX + "]"); +console.log("\n\nSizeY : " + sizeY); +console.log("UNIQUE Y VALUES:"); +console.log("[" + uniqueY + "]"); +console.log("\n\n\n\n\n\n"); + +let x: number = 1500, y: number = 1500, c_val: number = 0; +var c_filter: Segment[] = []; +function filterC(to: number): void { + c_filter = dataBlocks.filter((x: Segment) => + { + let y: Dimension | null = getDimension(x, 'C'); + if (y != null && y.Start == to) { + return y; + } + }); } +filterC(0); + +console.log("\n\nC Value: " + c_val + " TileSize: " + tileSize + " TileOverlap: " + tileOverlap + " Coords: " + `[X=${x}, Y=${y}]\nResults: `); +console.log(findRelatedTiles(c_filter, x, y).map((x: Segment) => x.Data.Data)); + +filterC(c_val = 1); +console.log("\n\nC Value: " + c_val + " TileSize: " + tileSize + " TileOverlap: " + tileOverlap + " Coords: " + `[X=${x}, Y=${y}]\nResults: `); +console.log(findRelatedTiles(c_filter, x, y).map((x: Segment) => x.Data.Data)); + +filterC(c_val = 0); x=0;y=0; +console.log("\n\nC Value: " + c_val + " TileSize: " + tileSize + " TileOverlap: " + tileOverlap + " Coords: " + `[X=${x}, Y=${y}]\nResults: `); +console.log(findRelatedTiles(c_filter, x, y).map((x: Segment) => x.Data.Data)); + +filterC(c_val = 0); x=41940;y=59240; +console.log("\n\nC Value: " + c_val + " TileSize: " + tileSize + " TileOverlap: " + tileOverlap + " Coords: " + `[X=${x}, Y=${y}]\nResults: `); +console.log(findRelatedTiles(c_filter, x, y).map((x: Segment) => x.Data.Data)); + +filterC(c_val = 0); x=41945;y=59245; +console.log("\n\nC Value: " + c_val + " TileSize: " + tileSize + " TileOverlap: " + tileOverlap + " Coords: " + `[X=${x}, Y=${y}]\nResults: `); +console.log(findRelatedTiles(c_filter, x, y).map((x: Segment) => x.Data.Data)); -- cgit v1.2.1 From 9f1ec11a7fd82939a48a4cad60b5eaa900f261b8 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Mon, 5 Mar 2018 20:54:47 +0000 Subject: Small touchups of czi inspector for modularity and readability --- src/conversion/czi/czi.ts | 90 +++++++++++++++++++---------------------------- 1 file changed, 36 insertions(+), 54 deletions(-) (limited to 'src/conversion/czi') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 720d711..df61033 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -64,7 +64,7 @@ function getOriginalTileBounds(originalTile: Segment): TileBounds | null { } -function findRelatedTiles(activeSegments: Segment[], desiredX: number, desiredY: number): Segment[] { +function findRelatedTiles(activeSegments: Segment[], desired: TileBounds): Segment[] { let relatedTiles: Segment[] = []; @@ -76,13 +76,6 @@ function findRelatedTiles(activeSegments: Segment[], desiredX: number, desiredY: throw new Error("There was a Sad Boi error"); } - let desired = new TileBounds( - desiredX - tileOverlap, - desiredX + tileSize + tileOverlap, - desiredY - tileOverlap, - desiredY + tileSize + tileOverlap - ); - //desired X on left is within current tile if (((desired.left >= origCoords.left) && (desired.left <= origCoords.right)) || @@ -118,13 +111,13 @@ function findRelatedTiles(activeSegments: Segment[], desiredX: number, desiredY: } -function getDimension(segment:Segment, name:string): Dimension | null { +function getDimension(segment:Segment, name:string): Dimension { for (let dimension of segment.Data.DirectoryEntry.DimensionEntries) { if (dimension.Dimension == name) { return dimension; } } - return null; + throw new Error("Dimension: " + name + " doesn't exist for segment: " + segment); } @@ -138,17 +131,8 @@ function getDimension(segment:Segment, name:string): Dimension | null { //Get all values of X and Y respectively. -let filterX: number[] = dataBlocks.map((x: Segment) => - { - let y: Dimension | null = getDimension(x, 'X'); - return y == null ? -1 : y.Start - }); -let filterY: number[] = dataBlocks.map((x: Segment) => - { - let y: Dimension | null = getDimension(x, 'Y'); - return y == null ? -1 : y.Start - }); - +let filterX: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'X').Start); +let filterY: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'Y').Start); //Filter all values to only keep the unique ones for X and Y coords respectively. let uniqueX: number[] = filterX.filter(function(elem: any, pos: any) { @@ -162,26 +146,18 @@ let uniqueY: number[] = filterY.filter(function(elem: any, pos: any) { However for the sake of hacking around, assume that the tiles in memory are going from left to right; top to bottom. like a book, then use this in order to count up the total size (in pixels) of the image*/ -let sizeX: number = 0; -let sizeY: number = 0; +let sizeX: number = 0, sizeY: number = 0; for (let i: number = 0; i < uniqueX.length; i++) { - let temp : Dimension | null = getDimension(dataBlocks[i], 'X'); - if (temp != null) { - sizeX += temp.Size; - } + sizeX += getDimension(dataBlocks[i], 'X').Size; }; for (let i: number = 0; i < uniqueY.length; i++) { - let temp : Dimension | null = getDimension(dataBlocks[i * uniqueX.length], 'Y'); - if (temp != null) - sizeY += temp.Size; + sizeX += getDimension(dataBlocks[i], 'Y').Size; }; -tileOverlap let uniqueTileSizes: number[][] = []; for (let seg of dataBlocks) { - let newx = getDimension(seg, 'X'), newy = getDimension(seg, 'Y'); - if (newx == null || newy == null) {continue;}; - let x: number = newx.Size, y: number = newy.Size; + + let x: number = getDimension(seg, 'X').Size, y: number = getDimension(seg, 'Y').Size; let found: boolean = false; for (let dimPair of uniqueTileSizes) { if (x == dimPair[0] && y == dimPair[1]) { @@ -203,16 +179,15 @@ for (let seg of dataBlocks) { // `npm bin`/ts-node czi.ts console.log("\n\nUnique Tile Sizes:"); console.log(uniqueTileSizes); -console.log("\n\nSizeX : " + sizeX); +console.log("\n\n(tentative) SizeX : " + sizeX); console.log("UNIQUE X VALUES:"); console.log("[" + uniqueX + "]"); -console.log("\n\nSizeY : " + sizeY); +console.log("\n\n(tentative) SizeY : " + sizeY); console.log("UNIQUE Y VALUES:"); -console.log("[" + uniqueY + "]"); -console.log("\n\n\n\n\n\n"); +console.log("[" + uniqueY + "]\n\n"); let x: number = 1500, y: number = 1500, c_val: number = 0; -var c_filter: Segment[] = []; +let c_filter: Segment[] = []; function filterC(to: number): void { c_filter = dataBlocks.filter((x: Segment) => { @@ -222,23 +197,30 @@ function filterC(to: number): void { } }); } -filterC(0); +let desired = new TileBounds (0,0,0,0); + +function runTest(cval: number, tilesize:number, tileoverlap:number, x1:number, y1:number) { + desired = new TileBounds ( + x1 - tileoverlap, + x1 + tilesize + tileoverlap, + y1 - tileoverlap, + y1 + tilesize + tileoverlap + ); + filterC(cval); + console.log("\n\nC Value: " + cval + " TileSize: " + tilesize + " TileOverlap(px): " + tileoverlap + " Coords: " + `[X=${x1}, Y=${y1}]\nResults: `); + console.log(findRelatedTiles(c_filter, desired).map((x: Segment) => x.Data.Data)); +} + +runTest(0, 1024, 5, 1500, 1500); + +runTest(1, 5000, 5, 1500, 1500); -console.log("\n\nC Value: " + c_val + " TileSize: " + tileSize + " TileOverlap: " + tileOverlap + " Coords: " + `[X=${x}, Y=${y}]\nResults: `); -console.log(findRelatedTiles(c_filter, x, y).map((x: Segment) => x.Data.Data)); +runTest(0, 1024, 5, 0, 0); -filterC(c_val = 1); -console.log("\n\nC Value: " + c_val + " TileSize: " + tileSize + " TileOverlap: " + tileOverlap + " Coords: " + `[X=${x}, Y=${y}]\nResults: `); -console.log(findRelatedTiles(c_filter, x, y).map((x: Segment) => x.Data.Data)); +runTest(0, 1024, 5, 41940, 59240); -filterC(c_val = 0); x=0;y=0; -console.log("\n\nC Value: " + c_val + " TileSize: " + tileSize + " TileOverlap: " + tileOverlap + " Coords: " + `[X=${x}, Y=${y}]\nResults: `); -console.log(findRelatedTiles(c_filter, x, y).map((x: Segment) => x.Data.Data)); +runTest(0, 1024, 5, -tileSize - tileOverlap -1, 59240); -filterC(c_val = 0); x=41940;y=59240; -console.log("\n\nC Value: " + c_val + " TileSize: " + tileSize + " TileOverlap: " + tileOverlap + " Coords: " + `[X=${x}, Y=${y}]\nResults: `); -console.log(findRelatedTiles(c_filter, x, y).map((x: Segment) => x.Data.Data)); +runTest(0, 1024, 5, 41945, 59245); -filterC(c_val = 0); x=41945;y=59245; -console.log("\n\nC Value: " + c_val + " TileSize: " + tileSize + " TileOverlap: " + tileOverlap + " Coords: " + `[X=${x}, Y=${y}]\nResults: `); -console.log(findRelatedTiles(c_filter, x, y).map((x: Segment) => x.Data.Data)); +runTest(3, 1024, 5, 41940, 1500); -- cgit v1.2.1 From c7e95511d3f633e3c761456f69bb3d65ed98b238 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Mon, 5 Mar 2018 22:50:50 +0000 Subject: small cleanup of things that wern't working, SAD COMMIT as need to look into another library for combining the images together --- src/conversion/czi/czi.ts | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src/conversion/czi') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index df61033..9ca9ad7 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -224,3 +224,10 @@ runTest(0, 1024, 5, -tileSize - tileOverlap -1, 59240); runTest(0, 1024, 5, 41945, 59245); runTest(3, 1024, 5, 41940, 1500); + + + +filterC(0); +console.log("\n\n\n\n\n\n\n"); + +//begin work on getting the new tiles all nice -- cgit v1.2.1 From 0ec15d6185ba07d9a3df3cf43443ae5c056f7c7d Mon Sep 17 00:00:00 2001 From: cjd24 Date: Tue, 6 Mar 2018 21:32:17 +0000 Subject: Committing to get the logger stuff --- src/conversion/czi/czi.ts | 159 ++++++++++++++++++++-------------------------- 1 file changed, 68 insertions(+), 91 deletions(-) (limited to 'src/conversion/czi') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 9ca9ad7..bb998ad 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -1,5 +1,5 @@ -let json: any = require('/cs/scratch/cjd24/0701-extraction/outputjson.json'); -json = json.czi; +// tslint:disable-next-line +let json: Segment[] = require('/cs/scratch/cjd24/0701-extraction/outputjson.json').czi; let tileOverlap: number = 5; let tileSize: number = 1024; @@ -23,36 +23,36 @@ interface Segment { Data: SubBlock; } class TileBounds { - left: number; - right: number; - top: number; - bottom: number; - constructor(left: number, right: number, top: number, bottom: number) { + public left: number; + public right: number; + public top: number; + public bottom: number; + public constructor(left: number, right: number, top: number, bottom: number) { this.left = left; this.right = right; this.top = top; this.bottom = bottom; - }; + } } - -//Get all subblocks that have an associated saved tile -let dataBlocks: Segment[] = json.filter((x: Segment) => x.Id == 'ZISRAWSUBBLOCK' && x.Data.Data != 'empty'); - +// Get all subblocks that have an associated saved tile +let dataBlocks: Segment[] = json.filter((s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'); function getOriginalTileBounds(originalTile: Segment): TileBounds | null { - let bounds: TileBounds = new TileBounds (-1, -1, -1, -1); - - for (let dimension of originalTile.Data.DirectoryEntry.DimensionEntries) { - if (dimension.Dimension == 'X') { - bounds.left = dimension.Start; - bounds.right = bounds.left + dimension.Size; - continue; - } - else if (dimension.Dimension == 'Y') { - bounds.top = dimension.Start; - bounds.bottom = bounds.top + dimension.Size; - continue; + const bounds: TileBounds = new TileBounds (-1, -1, -1, -1); + + for (const dimension of originalTile.Data.DirectoryEntry.DimensionEntries) { + switch (dimension.Dimension) { + case 'X': + bounds.left = dimension.Start; + bounds.right = bounds.left + dimension.Size; + continue; + case 'Y': + bounds.top = dimension.Start; + bounds.bottom = bounds.top + dimension.Size; + continue; + default: + continue; } } @@ -63,45 +63,39 @@ function getOriginalTileBounds(originalTile: Segment): TileBounds | null { return bounds; } - function findRelatedTiles(activeSegments: Segment[], desired: TileBounds): Segment[] { - let relatedTiles: Segment[] = []; + const relatedTiles: Segment[] = []; - - for (let origTile of activeSegments) { + for (const origTile of activeSegments) { let origCoords: TileBounds | null; if ((origCoords = getOriginalTileBounds(origTile)) === null) { - throw new Error("There was a Sad Boi error"); + throw new Error('There was a Sad Boi error'); } - //desired X on left is within current tile + // 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 X on right is within the current tile ((desired.right >= origCoords.left) && (desired.right <= origCoords.right)) || - //desired tile X overlaps base tile + // Desired tile X overlaps base tile ((desired.left < origCoords.left) && - (desired.right > origCoords.right))) - - { - //desired Y on top is within current tile + (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 Y on right is within the current tile ((desired.bottom >= origCoords.top) && (desired.bottom <= origCoords.bottom)) || - //desired tile Y overlaps whole base tile + // Desired tile Y overlaps whole base tile ((desired.top < origCoords.top) && - (desired.bottom > origCoords.bottom))) - - { + (desired.bottom > origCoords.bottom))) { relatedTiles.push(origTile); } } @@ -110,57 +104,48 @@ function findRelatedTiles(activeSegments: Segment[], desired: TileBounds): Segme return relatedTiles; } - -function getDimension(segment:Segment, name:string): Dimension { - for (let dimension of segment.Data.DirectoryEntry.DimensionEntries) { +function getDimension(segment: Segment, name: string): Dimension { + for (const dimension of segment.Data.DirectoryEntry.DimensionEntries) { if (dimension.Dimension == name) { return dimension; } } - throw new Error("Dimension: " + name + " doesn't exist for segment: " + segment); + throw new Error('Dimension: ' + name + " doesn't exist for segment: " + segment); } - - - - - - - - - - -//Get all values of X and Y respectively. +// Get all values of X and Y respectively. let filterX: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'X').Start); let filterY: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'Y').Start); -//Filter all values to only keep the unique ones for X and Y coords respectively. +// Filter all values to only keep the unique ones for X and Y coords respectively. let uniqueX: number[] = filterX.filter(function(elem: any, pos: any) { - return filterX.indexOf(elem) == pos; + return filterX.indexOf(elem) === pos; }); let uniqueY: number[] = filterY.filter(function(elem: any, pos: any) { - return filterY.indexOf(elem) == pos; + return filterY.indexOf(elem) === pos; }); /*These values are normally stored at the big XML metadata under "Information/Image/SizeX or SizeY"; However for the sake of hacking around, assume that the tiles in memory are going from left to right; top to bottom. like a book, then use this in order to count up the total size (in pixels) of the image*/ -let sizeX: number = 0, sizeY: number = 0; +let sizeX: number = 0; +let sizeY: number = 0; for (let i: number = 0; i < uniqueX.length; i++) { sizeX += getDimension(dataBlocks[i], 'X').Size; -}; +} for (let i: number = 0; i < uniqueY.length; i++) { sizeX += getDimension(dataBlocks[i], 'Y').Size; -}; +} let uniqueTileSizes: number[][] = []; -for (let seg of dataBlocks) { +for (const seg of dataBlocks) { - let x: number = getDimension(seg, 'X').Size, y: number = getDimension(seg, 'Y').Size; + const x: number = getDimension(seg, 'X').Size; + const y: number = getDimension(seg, 'Y').Size; let found: boolean = false; - for (let dimPair of uniqueTileSizes) { - if (x == dimPair[0] && y == dimPair[1]) { + for (const dimPair of uniqueTileSizes) { + if (x === dimPair[0] && y === dimPair[1]) { found = true; break; } @@ -168,38 +153,32 @@ for (let seg of dataBlocks) { if (!found) { uniqueTileSizes.push([x, y]); } -}; - - - - - +} -//TESTS TO SEE WHAT VARIOUS THINGS RETURN +// TESTS TO SEE WHAT VARIOUS THINGS RETURN // `npm bin`/ts-node czi.ts -console.log("\n\nUnique Tile Sizes:"); +console.log('\n\nUnique Tile Sizes:'); console.log(uniqueTileSizes); -console.log("\n\n(tentative) SizeX : " + sizeX); -console.log("UNIQUE X VALUES:"); -console.log("[" + uniqueX + "]"); -console.log("\n\n(tentative) SizeY : " + sizeY); -console.log("UNIQUE Y VALUES:"); -console.log("[" + uniqueY + "]\n\n"); +console.log('\n\n(tentative) SizeX : ' + sizeX); +console.log('UNIQUE X VALUES:'); +console.log('[' + uniqueX + ']'); +console.log('\n\n(tentative) SizeY : ' + sizeY); +console.log('UNIQUE Y VALUES:'); +console.log('[' + uniqueY + ']\n\n'); let x: number = 1500, y: number = 1500, c_val: number = 0; let c_filter: Segment[] = []; function filterC(to: number): void { - c_filter = dataBlocks.filter((x: Segment) => - { - let y: Dimension | null = getDimension(x, 'C'); + c_filter = dataBlocks.filter((x: Segment) => { + const y: Dimension | null = getDimension(x, 'C'); if (y != null && y.Start == to) { return y; } }); } -let desired = new TileBounds (0,0,0,0); +let desired = new TileBounds (0, 0, 0, 0); -function runTest(cval: number, tilesize:number, tileoverlap:number, x1:number, y1:number) { +function runTest(cval: number, tilesize: number, tileoverlap: number, x1: number, y1: number) { desired = new TileBounds ( x1 - tileoverlap, x1 + tilesize + tileoverlap, @@ -207,7 +186,7 @@ function runTest(cval: number, tilesize:number, tileoverlap:number, x1:number, y y1 + tilesize + tileoverlap ); filterC(cval); - console.log("\n\nC Value: " + cval + " TileSize: " + tilesize + " TileOverlap(px): " + tileoverlap + " Coords: " + `[X=${x1}, Y=${y1}]\nResults: `); + console.log('\n\nC Value: ' + cval + ' TileSize: ' + tilesize + ' TileOverlap(px): ' + tileoverlap + ' Coords: ' + `[X=${x1}, Y=${y1}]\nResults: `); console.log(findRelatedTiles(c_filter, desired).map((x: Segment) => x.Data.Data)); } @@ -219,15 +198,13 @@ runTest(0, 1024, 5, 0, 0); runTest(0, 1024, 5, 41940, 59240); -runTest(0, 1024, 5, -tileSize - tileOverlap -1, 59240); +runTest(0, 1024, 5, -tileSize - tileOverlap - 1, 59240); runTest(0, 1024, 5, 41945, 59245); runTest(3, 1024, 5, 41940, 1500); - - filterC(0); -console.log("\n\n\n\n\n\n\n"); +console.log('\n\n\n\n\n\n\n'); -//begin work on getting the new tiles all nice +// Begin work on getting the new tiles all nice -- cgit v1.2.1 From bfc14f0a5a95351c9d800248886fd0887197fdd9 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Wed, 7 Mar 2018 01:15:34 +0000 Subject: Added ordering support for base tiles, now need to cut out chunks and stitch tiles --- src/conversion/czi/czi.ts | 215 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 171 insertions(+), 44 deletions(-) (limited to 'src/conversion/czi') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index bb998ad..c924673 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -1,8 +1,6 @@ -// tslint:disable-next-line -let json: Segment[] = require('/cs/scratch/cjd24/0701-extraction/outputjson.json').czi; -let tileOverlap: number = 5; -let tileSize: number = 1024; +import { logger } from '../../logger'; +import * as sharp from 'sharp'; interface Dimension { Dimension: string; @@ -23,23 +21,25 @@ interface Segment { Data: SubBlock; } class TileBounds { - public left: number; - public right: number; - public top: number; - public bottom: number; - public constructor(left: number, right: number, top: number, bottom: number) { - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; + 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; } } -// Get all subblocks that have an associated saved tile -let dataBlocks: Segment[] = json.filter((s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'); +const extractionDirectory: string = '/cs/scratch/cjd24/0701-extraction/'; +const json: Segment[] = require(`${extractionDirectory}outputjson.json`).czi; +const tileOverlap: number = 0; +const tileSize: number = 1024; -function getOriginalTileBounds(originalTile: Segment): TileBounds | null { - const bounds: TileBounds = new TileBounds (-1, -1, -1, -1); +const getOriginalTileBounds = function(originalTile: Segment): (TileBounds | null) { + const bounds: TileBounds = new TileBounds(-1, -1, -1, -1); for (const dimension of originalTile.Data.DirectoryEntry.DimensionEntries) { switch (dimension.Dimension) { @@ -63,40 +63,42 @@ function getOriginalTileBounds(originalTile: Segment): TileBounds | null { return bounds; } -function findRelatedTiles(activeSegments: Segment[], desired: TileBounds): Segment[] { +const findRelatedTiles = function(activeSegments: Segment[], desired: TileBounds): Segment[] { const relatedTiles: Segment[] = []; - for (const origTile of activeSegments) { + for (const baseTile of activeSegments) { let origCoords: TileBounds | null; - if ((origCoords = getOriginalTileBounds(origTile)) === null) { + if ((origCoords = getOriginalTileBounds(baseTile)) === null) { throw new Error('There was a Sad Boi error'); } - // Desired X on left is within current tile + // 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.right <= origCoords.right)) || // Desired tile X overlaps base tile ((desired.left < origCoords.left) && - (desired.right > origCoords.right))) { + (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.bottom <= origCoords.bottom)) || // Desired tile Y overlaps whole base tile ((desired.top < origCoords.top) && - (desired.bottom > origCoords.bottom))) { - relatedTiles.push(origTile); + (desired.bottom > origCoords.bottom))) { + + relatedTiles.push(baseTile); } } } @@ -104,7 +106,7 @@ function findRelatedTiles(activeSegments: Segment[], desired: TileBounds): Segme return relatedTiles; } -function getDimension(segment: Segment, name: string): Dimension { +const getDimension = function(segment: Segment, name: string): Dimension { for (const dimension of segment.Data.DirectoryEntry.DimensionEntries) { if (dimension.Dimension == name) { return dimension; @@ -113,15 +115,93 @@ function getDimension(segment: Segment, name: string): Dimension { throw new Error('Dimension: ' + name + " doesn't exist for segment: " + segment); } +const orderSegments = function(segments: Segment[]): Segment[][] { + + const output: Segment[][] = []; + + if (segments.length > 1) { + let xCoords: number[] = []; + let yCoords: number[] = []; + + // Get all x/y's; + 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"); + } + 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); + + // Use the filtered list to order the segments into rows + for (const yVal of yCoords) { + + // Get all segments with the same y value + const row: Segment[] = []; + for (const seg of segments) { + if (getDimension(seg, 'Y').Start === yVal) { + row.push(seg); + } + } + + // Sort the row of y values by x value + const sortedRow: Segment[] = []; + for (const xVal of xCoords) { + for (const seg of row) { + if (getDimension(seg, 'X').Start === xVal) { + sortedRow.push(seg); + break; + } + } + } + + // Push this to the finalised grid + output.push(sortedRow); + } + + // Return the result + return output; + } + else { + output.push(segments); + return output; + } +} + + + + + + + + + + + + + + + + + + + + +// Get all subblocks that have an associated saved tile +const dataBlocks: Segment[] = json.filter((s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'); + // Get all values of X and Y respectively. -let filterX: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'X').Start); -let filterY: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'Y').Start); +const filterX: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'X').Start); +const filterY: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'Y').Start); // Filter all values to only keep the unique ones for X and Y coords respectively. -let uniqueX: number[] = filterX.filter(function(elem: any, pos: any) { +const uniqueX: number[] = filterX.filter(function(elem: any, pos: any) { return filterX.indexOf(elem) === pos; }); -let uniqueY: number[] = filterY.filter(function(elem: any, pos: any) { +const uniqueY: number[] = filterY.filter(function(elem: any, pos: any) { return filterY.indexOf(elem) === pos; }); @@ -135,10 +215,10 @@ for (let i: number = 0; i < uniqueX.length; i++) { sizeX += getDimension(dataBlocks[i], 'X').Size; } for (let i: number = 0; i < uniqueY.length; i++) { - sizeX += getDimension(dataBlocks[i], 'Y').Size; + sizeY += getDimension(dataBlocks[i], 'Y').Size; } -let uniqueTileSizes: number[][] = []; +const uniqueTileSizes: number[][] = []; for (const seg of dataBlocks) { const x: number = getDimension(seg, 'X').Size; @@ -155,8 +235,8 @@ for (const seg of dataBlocks) { } } -// TESTS TO SEE WHAT VARIOUS THINGS RETURN -// `npm bin`/ts-node czi.ts +// // TESTS TO SEE WHAT VARIOUS THINGS RETURN +// // `npm bin`/ts-node czi.ts console.log('\n\nUnique Tile Sizes:'); console.log(uniqueTileSizes); console.log('\n\n(tentative) SizeX : ' + sizeX); @@ -176,9 +256,9 @@ function filterC(to: number): void { } }); } -let desired = new TileBounds (0, 0, 0, 0); -function runTest(cval: number, tilesize: number, tileoverlap: number, x1: number, y1: number) { +let desired = new TileBounds (0, 0, 0, 0); +function findRelatedTest(cval: number, tilesize: number, tileoverlap: number, x1: number, y1: number) { desired = new TileBounds ( x1 - tileoverlap, x1 + tilesize + tileoverlap, @@ -190,21 +270,68 @@ function runTest(cval: number, tilesize: number, tileoverlap: number, x1: number console.log(findRelatedTiles(c_filter, desired).map((x: Segment) => x.Data.Data)); } -runTest(0, 1024, 5, 1500, 1500); +findRelatedTest(0, 1024, 5, 1500, 1500); -runTest(1, 5000, 5, 1500, 1500); +findRelatedTest(1, 5000, 5, 1500, 1500); -runTest(0, 1024, 5, 0, 0); +findRelatedTest(0, 1024, 5, 0, 0); -runTest(0, 1024, 5, 41940, 59240); +findRelatedTest(0, 1024, 5, 41940, 59240); -runTest(0, 1024, 5, -tileSize - tileOverlap - 1, 59240); +findRelatedTest(0, 1024, 5, -tileSize - tileOverlap - 1, 59240); -runTest(0, 1024, 5, 41945, 59245); +findRelatedTest(0, 1024, 5, 41945, 59245); -runTest(3, 1024, 5, 41940, 1500); +findRelatedTest(3, 1024, 5, 41940, 1500); filterC(0); console.log('\n\n\n\n\n\n\n'); + + + + + + + + + + + + + + + + + + + + // Begin work on getting the new tiles all nice +function sortSegmentsTest(cval: number, tilesize: number, tileoverlap: number, x1: number, y1: number) { + desired = new TileBounds ( + x1 - tileoverlap, + x1 + tilesize + tileoverlap, + y1 - tileoverlap, + y1 + tilesize + tileoverlap + ); + filterC(cval); + console.log('\nC Value: ' + cval + ' TileSize: ' + tilesize + ' TileOverlap(px): ' + tileoverlap + ' Coords: ' + `[X=${x1}, Y=${y1}]`); + let outputGrid: Segment[][] = orderSegments(findRelatedTiles(c_filter, desired)); + + for (const row of outputGrid) { + let rowOutput: string = "[ "; + for (const col of row) { + rowOutput += ` '${col.Data.Data}', `; + } + rowOutput += ']'; + console.log(rowOutput); + } +} + + +for (let ys: number = 0; ys < sizeY; ys += tileSize) { + for (let xs: number = 0; xs < sizeX; xs += tileSize) { + sortSegmentsTest(0, tileSize, tileOverlap, xs, ys); + } +} -- cgit v1.2.1 From 79e192389adaf4368dcd3103bc2a633444fc990f Mon Sep 17 00:00:00 2001 From: cjd24 Date: Wed, 7 Mar 2018 03:21:14 +0000 Subject: fixed some random problems everywhere, and made typescript a little happier with czi.ts and XMLparsed to get max x and y instead of janky unreliable thing --- src/conversion/czi/czi.ts | 133 ++++++++++++++++++++++++---------------------- 1 file changed, 69 insertions(+), 64 deletions(-) (limited to 'src/conversion/czi') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index c924673..a52508a 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -1,6 +1,12 @@ +import * as fs from 'fs'; import { logger } from '../../logger'; import * as sharp from 'sharp'; +import * as parsexml from 'xml-parser'; + +const extractionDirectory: string = '/cs/scratch/cjd24/0701-extraction/'; +const tileOverlap: number = 0; +const tileSize: number = 1024; interface Dimension { Dimension: string; @@ -33,12 +39,7 @@ class TileBounds { } } -const extractionDirectory: string = '/cs/scratch/cjd24/0701-extraction/'; -const json: Segment[] = require(`${extractionDirectory}outputjson.json`).czi; -const tileOverlap: number = 0; -const tileSize: number = 1024; - -const getOriginalTileBounds = function(originalTile: Segment): (TileBounds | null) { +const getOriginalTileBounds: Function = function(originalTile: Segment): (TileBounds | null) { const bounds: TileBounds = new TileBounds(-1, -1, -1, -1); for (const dimension of originalTile.Data.DirectoryEntry.DimensionEntries) { @@ -61,9 +62,9 @@ const getOriginalTileBounds = function(originalTile: Segment): (TileBounds | nul } return bounds; -} +}; -const findRelatedTiles = function(activeSegments: Segment[], desired: TileBounds): Segment[] { +const findRelatedTiles: Function = function(activeSegments: Segment[], desired: TileBounds): Segment[] { const relatedTiles: Segment[] = []; for (const baseTile of activeSegments) { @@ -104,18 +105,18 @@ const findRelatedTiles = function(activeSegments: Segment[], desired: TileBounds } return relatedTiles; -} +}; -const getDimension = function(segment: Segment, name: string): Dimension { +const getDimension: Function = function(segment: Segment, name: string): Dimension { for (const dimension of segment.Data.DirectoryEntry.DimensionEntries) { - if (dimension.Dimension == name) { + if (dimension.Dimension === name) { return dimension; } } throw new Error('Dimension: ' + name + " doesn't exist for segment: " + segment); -} +}; -const orderSegments = function(segments: Segment[]): Segment[][] { +const orderSegments: Function = function(segments: Segment[]): Segment[][] { const output: Segment[][] = []; @@ -133,8 +134,10 @@ const orderSegments = function(segments: Segment[]): Segment[][] { 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); + 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); // Use the filtered list to order the segments into rows for (const yVal of yCoords) { @@ -164,12 +167,11 @@ const orderSegments = function(segments: Segment[]): Segment[][] { // Return the result return output; - } - else { + } else { output.push(segments); return output; } -} +}; @@ -189,35 +191,41 @@ const orderSegments = function(segments: Segment[]): Segment[][] { +const dataBlocks: Segment[] = require(`${extractionDirectory}outputjson.json`).czi.filter( + (s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'); +const inspect: object = require('util').inspect; +const metaXML: parsexml.Node[] = parsexml(fs.readFileSync(`${extractionDirectory}FILE-META-1.xml`, 'utf8')).root.children; -// Get all subblocks that have an associated saved tile -const dataBlocks: Segment[] = json.filter((s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'); +let totalSizeX: number = -1; +let totalSizeY: number = -1; -// Get all values of X and Y respectively. -const filterX: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'X').Start); -const filterY: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'Y').Start); - -// Filter all values to only keep the unique ones for X and Y coords respectively. -const uniqueX: number[] = filterX.filter(function(elem: any, pos: any) { - return filterX.indexOf(elem) === pos; -}); -const uniqueY: number[] = filterY.filter(function(elem: any, pos: any) { - return filterY.indexOf(elem) === pos; -}); - -/*These values are normally stored at the big XML metadata under "Information/Image/SizeX or SizeY"; -However for the sake of hacking around, assume that the tiles in memory are -going from left to right; top to bottom. like a book, then use this in order -to count up the total size (in pixels) of the image*/ -let sizeX: number = 0; -let sizeY: number = 0; -for (let i: number = 0; i < uniqueX.length; i++) { - sizeX += getDimension(dataBlocks[i], 'X').Size; -} -for (let i: number = 0; i < uniqueY.length; i++) { - sizeY += getDimension(dataBlocks[i], 'Y').Size; +// 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) { + 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); + } else if (property.name === 'SizeY' && property.content) { + totalSizeY = Number.parseInt(property.content, 10); + } + } + } + } + } + } + } } +// 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) { @@ -239,23 +247,23 @@ for (const seg of dataBlocks) { // // `npm bin`/ts-node czi.ts console.log('\n\nUnique Tile Sizes:'); console.log(uniqueTileSizes); -console.log('\n\n(tentative) SizeX : ' + sizeX); +console.log('\n\nSizeX : ' + totalSizeX); console.log('UNIQUE X VALUES:'); -console.log('[' + uniqueX + ']'); -console.log('\n\n(tentative) SizeY : ' + sizeY); +console.log(uniqueX); +console.log('\n\n(tentative) SizeY : ' + totalSizeY); console.log('UNIQUE Y VALUES:'); -console.log('[' + uniqueY + ']\n\n'); +console.log(uniqueY); -let x: number = 1500, y: number = 1500, c_val: number = 0; +let x: number = 1500, y: number = 1500; let c_filter: Segment[] = []; -function filterC(to: number): void { +const filterC: Function = function(to: number): void { c_filter = dataBlocks.filter((x: Segment) => { const y: Dimension | null = getDimension(x, 'C'); - if (y != null && y.Start == to) { + if (y != null && y.Start === to) { return y; } }); -} +}; let desired = new TileBounds (0, 0, 0, 0); function findRelatedTest(cval: number, tilesize: number, tileoverlap: number, x1: number, y1: number) { @@ -300,15 +308,10 @@ console.log('\n\n\n\n\n\n\n'); - - - - - - +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Begin work on getting the new tiles all nice -function sortSegmentsTest(cval: number, tilesize: number, tileoverlap: number, x1: number, y1: number) { +const sortSegmentsTest: Function = function(cval: number, tilesize: number, tileoverlap: number, x1: number, y1: number): Segment[][] { desired = new TileBounds ( x1 - tileoverlap, x1 + tilesize + tileoverlap, @@ -317,21 +320,23 @@ function sortSegmentsTest(cval: number, tilesize: number, tileoverlap: number, x ); filterC(cval); console.log('\nC Value: ' + cval + ' TileSize: ' + tilesize + ' TileOverlap(px): ' + tileoverlap + ' Coords: ' + `[X=${x1}, Y=${y1}]`); - let outputGrid: Segment[][] = orderSegments(findRelatedTiles(c_filter, desired)); + const outputGrid: Segment[][] = orderSegments(findRelatedTiles(c_filter, desired)); for (const row of outputGrid) { - let rowOutput: string = "[ "; + let rowOutput: string = '[ '; for (const col of row) { rowOutput += ` '${col.Data.Data}', `; } rowOutput += ']'; console.log(rowOutput); } -} + return outputGrid; +}; +// Print out all of the related tiles to every new tile to be created. +for (let ys: number = 0; ys < totalSizeY; ys += tileSize) { + for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { + const sortedSegments: Segment[][] = sortSegmentsTest(0, tileSize, tileOverlap, xs, ys); -for (let ys: number = 0; ys < sizeY; ys += tileSize) { - for (let xs: number = 0; xs < sizeX; xs += tileSize) { - sortSegmentsTest(0, tileSize, tileOverlap, xs, ys); } } -- cgit v1.2.1 From bd097386cf45f8afe4aa3bec863955bfed156394 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Wed, 7 Mar 2018 09:34:55 +0000 Subject: BASE LAYER EXTRACTION WORKS OMMMGGGG --- src/conversion/czi/czi.ts | 121 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 109 insertions(+), 12 deletions(-) (limited to 'src/conversion/czi') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index a52508a..7e39d68 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -3,8 +3,10 @@ import * as fs from 'fs'; import { logger } from '../../logger'; import * as sharp from 'sharp'; import * as parsexml from 'xml-parser'; +import { SharpInstance } from 'sharp'; const extractionDirectory: string = '/cs/scratch/cjd24/0701-extraction/'; +const outputImageDirectory: string = '/cs/scratch/cjd24/0701-extraction-processed/' const tileOverlap: number = 0; const tileSize: number = 1024; @@ -77,27 +79,27 @@ const findRelatedTiles: Function = function(activeSegments: Segment[], desired: // Desired X on left is within current tile if (((desired.left >= origCoords.left) && - (desired.left <= origCoords.right)) || + (desired.left < origCoords.right)) || // Desired X on right is within the current tile - ((desired.right >= origCoords.left) && - (desired.right <= origCoords.right)) || + ((desired.right > origCoords.left) && + (desired.right <= origCoords.right)) || // Desired tile X overlaps base tile ((desired.left < origCoords.left) && - (desired.right > origCoords.right))) { + (desired.right > origCoords.right))) { // Desired Y on top is within current tile if (((desired.top >= origCoords.top) && - (desired.top <= origCoords.bottom)) || + (desired.top < origCoords.bottom)) || // Desired Y on right is within the current tile - ((desired.bottom >= origCoords.top) && - (desired.bottom <= origCoords.bottom)) || + ((desired.bottom > origCoords.top) && + (desired.bottom <= origCoords.bottom)) || // Desired tile Y overlaps whole base tile ((desired.top < origCoords.top) && - (desired.bottom > origCoords.bottom))) { + (desired.bottom > origCoords.bottom))) { relatedTiles.push(baseTile); } @@ -173,6 +175,89 @@ const orderSegments: Function = function(segments: Segment[]): Segment[][] { } }; +const findRegionToExtract: Function = function(segment: Segment, desired: TileBounds): TileBounds { + const baseBounds: TileBounds = getOriginalTileBounds(segment); + let 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; +}; + +const extractAndStitchChunks: Function = async function(segments: Segment[][], desiredRegion: TileBounds): Promise { + + let tileVerticalBuffer: Buffer[] = []; + + for (const segRow of segments) { + let tileRow: Buffer[] = []; + let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); + for (const segCol of segRow) { + chunkToExtract = findRegionToExtract(segCol, desiredRegion); + let data: Promise = + sharp(`${extractionDirectory}${segCol.Data.Data}`) + .extract({ + left: chunkToExtract.left, + top: chunkToExtract.top, + width: chunkToExtract.right - chunkToExtract.left, + height: chunkToExtract.bottom - chunkToExtract.top + }) + .toBuffer(); + + tileRow.push(await data); + } + + let imageVerticalSlice: SharpInstance = sharp(tileRow[0]); + let bufferBound = findRegionToExtract(segRow[0], desiredRegion); + if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) { + imageVerticalSlice = await imageVerticalSlice.extend( + {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))}); + } + for (let index = 1; index < segRow.length; index++) { + imageVerticalSlice = imageVerticalSlice + .overlayWith(tileRow[index], + {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)}); + } + + tileVerticalBuffer.push(await imageVerticalSlice.toBuffer()); + } + + let finalImage: SharpInstance = sharp(tileVerticalBuffer[0]); + let bufferBound = findRegionToExtract(segments[0][0], desiredRegion); + if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) { + finalImage = await finalImage.extend( + {top:0, left:0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0}); + } + for (let index = 1; index < segments.length; index++) { + finalImage = finalImage.overlayWith( + tileVerticalBuffer[index], + {top: getDimension(segments[index -1][0], 'Y').Size, left: 0}); + } + + return finalImage; +}; + @@ -334,9 +419,21 @@ const sortSegmentsTest: Function = function(cval: number, tilesize: number, tile }; // Print out all of the related tiles to every new tile to be created. -for (let ys: number = 0; ys < totalSizeY; ys += tileSize) { - for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { - const sortedSegments: Segment[][] = sortSegmentsTest(0, tileSize, tileOverlap, xs, ys); - +let filecoutner: number = 0; +async function main(): Promise { + // temper: + for (let ys: number = 0; ys < totalSizeY; ys += tileSize) { + for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { + const sortedSegments: Segment[][] = sortSegmentsTest(0, tileSize, tileOverlap, xs, ys); + (await extractAndStitchChunks(sortedSegments, desired)).toFile(`${outputImageDirectory}img-${filecoutner++}`); + } + // break temper; } } + +main().then(v => { + //Write the json hierarchy map to file + console.log("complete"); +}, err => { + console.log(err); +}); -- cgit v1.2.1 From 7acbbac2bff4976a161ee724db91716659c1f881 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Wed, 7 Mar 2018 15:40:54 +0000 Subject: Adding support for the protocol's supported_views thing and laid base work for building up multi-dimentional hierarchy --- src/conversion/czi/czi.ts | 220 ++++++++++++++++++++++------------------------ 1 file changed, 106 insertions(+), 114 deletions(-) (limited to 'src/conversion/czi') diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 7e39d68..addf43e 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -6,9 +6,10 @@ import * as parsexml from 'xml-parser'; import { SharpInstance } from 'sharp'; const extractionDirectory: string = '/cs/scratch/cjd24/0701-extraction/'; -const outputImageDirectory: string = '/cs/scratch/cjd24/0701-extraction-processed/' +const outputImageDirectory: string = '/cs/scratch/cjd24/0701-extraction-processed2/' const tileOverlap: number = 0; const tileSize: number = 1024; +const maxZoom: number = 64; interface Dimension { Dimension: string; @@ -40,6 +41,45 @@ class TileBounds { 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 bounds: TileBounds = new TileBounds(-1, -1, -1, -1); @@ -130,7 +170,7 @@ const orderSegments: Function = function(segments: Segment[]): Segment[][] { 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); @@ -235,7 +275,7 @@ const extractAndStitchChunks: Function = async function(segments: Segment[][], d {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))}); } for (let index = 1; index < segRow.length; index++) { - imageVerticalSlice = imageVerticalSlice + imageVerticalSlice = await imageVerticalSlice .overlayWith(tileRow[index], {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)}); } @@ -261,31 +301,21 @@ const extractAndStitchChunks: Function = async function(segments: Segment[][], d - - - - - - - - - - - - - - +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const dataBlocks: Segment[] = require(`${extractionDirectory}outputjson.json`).czi.filter( (s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'); -const inspect: object = require('util').inspect; -const metaXML: parsexml.Node[] = parsexml(fs.readFileSync(`${extractionDirectory}FILE-META-1.xml`, 'utf8')).root.children; +const inspect = require('util').inspect; +const metaXML: parsexml.Document = parsexml(fs.readFileSync(`${extractionDirectory}FILE-META-1.xml`, 'utf8')); + +let supportedViews: SupportedViews = {scalable_image: {width: -1, height: -1, channels: [{channel_id: '-1', channel_name: ''}], metadata: metaXML}}; +supportedViews.scalable_image.channels.pop(); let totalSizeX: number = -1; let totalSizeY: number = -1; // 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) { +for (const child of metaXML.root.children) { if (child.name === 'Metadata') { for (const entry of child.children) { if (entry.name === 'Information') { @@ -294,8 +324,26 @@ for (const child of metaXML) { 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 + } + ); + } + } + } } } } @@ -328,112 +376,56 @@ for (const seg of dataBlocks) { } } -// // TESTS TO SEE WHAT VARIOUS THINGS RETURN -// // `npm bin`/ts-node czi.ts -console.log('\n\nUnique Tile Sizes:'); -console.log(uniqueTileSizes); -console.log('\n\nSizeX : ' + totalSizeX); -console.log('UNIQUE X VALUES:'); -console.log(uniqueX); -console.log('\n\n(tentative) SizeY : ' + totalSizeY); -console.log('UNIQUE Y VALUES:'); -console.log(uniqueY); - -let x: number = 1500, y: number = 1500; -let c_filter: Segment[] = []; +let filteredDataBlocks: Segment[] = []; const filterC: Function = function(to: number): void { - c_filter = dataBlocks.filter((x: Segment) => { - const y: Dimension | null = getDimension(x, 'C'); - if (y != null && y.Start === to) { - return y; - } - }); -}; - -let desired = new TileBounds (0, 0, 0, 0); -function findRelatedTest(cval: number, tilesize: number, tileoverlap: number, x1: number, y1: number) { - desired = new TileBounds ( - x1 - tileoverlap, - x1 + tilesize + tileoverlap, - y1 - tileoverlap, - y1 + tilesize + tileoverlap + filteredDataBlocks = dataBlocks.filter( + (item: Segment, index: number, array: Segment[]) => getDimension(item, 'C').Start === to ); - filterC(cval); - console.log('\n\nC Value: ' + cval + ' TileSize: ' + tilesize + ' TileOverlap(px): ' + tileoverlap + ' Coords: ' + `[X=${x1}, Y=${y1}]\nResults: `); - console.log(findRelatedTiles(c_filter, desired).map((x: Segment) => x.Data.Data)); -} - -findRelatedTest(0, 1024, 5, 1500, 1500); - -findRelatedTest(1, 5000, 5, 1500, 1500); - -findRelatedTest(0, 1024, 5, 0, 0); - -findRelatedTest(0, 1024, 5, 41940, 59240); - -findRelatedTest(0, 1024, 5, -tileSize - tileOverlap - 1, 59240); - -findRelatedTest(0, 1024, 5, 41945, 59245); - -findRelatedTest(3, 1024, 5, 41940, 1500); - -filterC(0); -console.log('\n\n\n\n\n\n\n'); - - - - - - - - - - - - +}; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Begin work on getting the new tiles all nice -const sortSegmentsTest: Function = function(cval: number, tilesize: number, tileoverlap: number, x1: number, y1: number): Segment[][] { - desired = new TileBounds ( - x1 - tileoverlap, - x1 + tilesize + tileoverlap, - y1 - tileoverlap, - y1 + tilesize + tileoverlap - ); - filterC(cval); - console.log('\nC Value: ' + cval + ' TileSize: ' + tilesize + ' TileOverlap(px): ' + tileoverlap + ' Coords: ' + `[X=${x1}, Y=${y1}]`); - const outputGrid: Segment[][] = orderSegments(findRelatedTiles(c_filter, desired)); - - for (const row of outputGrid) { - let rowOutput: string = '[ '; - for (const col of row) { - rowOutput += ` '${col.Data.Data}', `; - } - rowOutput += ']'; - console.log(rowOutput); - } - return outputGrid; -}; - // Print out all of the related tiles to every new tile to be created. let filecoutner: number = 0; -async function main(): Promise { - // temper: - for (let ys: number = 0; ys < totalSizeY; ys += tileSize) { +async function extrapolateDimension(cVal: number, totalCs: number, maxZoomLevel: number): Promise { + console.log(`Stage (${cVal + 1}/${totalCs}): Task(0/${Math.ceil(totalSizeY/tileSize)}): 0% complete.`) + for (let ys: number = 0; ys < totalSizeY;) { + var timing = process.hrtime(); for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { - const sortedSegments: Segment[][] = sortSegmentsTest(0, tileSize, tileOverlap, xs, ys); + const desired = 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++}`); } - // break temper; + 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 []; } -main().then(v => { - //Write the json hierarchy map to file - console.log("complete"); -}, err => { - console.log(err); -}); +let finalCZIJson: WholeCZIHierarchy = {} as any; +async function main(): Promise { + 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}`); + return; + }, err => { + console.error(err); + } + ); + } + fs.writeFile(`${outputImageDirectory}layout.json`, JSON.stringify(finalCZIJson), (err) => console.error(err)); +} +main(); -- cgit v1.2.1