def main(): imp = IJ.getFilePath("Select DCIMG file") if not imp: return root, ext = os.path.splitext(imp) if ext.lower() != '.dcimg': cFrame = PlugInFrame('ERR DLG') MessageDialog(cFrame, 'ERROR', 'Expected extension .dcimg') return #Lets start fID = open(imp, 'rb') hdr_bytes = read_header_bytes(fID) hdr = parse_header_bytes(fID, hdr_bytes) metadataStr = beginMetadata() for key, value in hdr.iteritems(): metadataStr += addMetadataEntry(key, str(value)) metadataStr += endMetadata() metadataDlg = HTMLDialog("DCIMG metadata", metadataStr, 0) size = metadataDlg.getSize() if size.width < 300: size.width = 300 if size.height < 500: size.height = 500 metadataDlg.setSize(size) finfo = FileInfo() finfo.fileName = imp #finfo.width = hdr['xsize_req'] finfo.width = hdr['xsize'] finfo.height = hdr['ysize'] finfo.nImages = hdr['nframes'] finfo.offset = 232 finfo.fileType = hdr['bitdepth'] / 8 - 1 #Ugh finfo.intelByteOrder = 1 #finfo.gapBetweenImages = int(hdr['bytes_per_img']*(1-float(hdr['xsize_req'])/float(hdr['xsize']))) finfo.gapBetweenImages = 0 finfo.fileFormat = 1 finfo.samplesPerPixel = 1 finfo.displayRanges = None finfo.lutSize = 0 finfo.whiteIsZero = 0 vs = VirtualStack() finfo.virtualStack = vs FileInfoVirtualStack(finfo)
imp.show() finally: cs.close() # Approach 3: using low-level ImageJ libraries from ij.io import FileInfo, FileOpener fi = FileInfo() fi.width = width fi.height = height fi.offset = headerSize + slice_offset # ASSUMES images aren't ARGB, which would also have 32 as bit depth # (There are other types: see FileInfo javadoc) fi.fileType = { 8: FileInfo.GRAY8, 16: FileInfo.GRAY16_UNSIGNED, 24: FileInfo.RGB, 32: FileInfo.GRAY32_UNSIGNED }[bitDepth] fi.samplesPerPixel = 1 fi.nImages = num_slices directory, filename = os.path.split(filepath) fi.directory = directory fi.fileName = filename imp = FileOpener(fi).openImage() # returns an ImagePlus imp.show() # Approach 4: with low-level java libraries from ij import ImagePlus, ImageStack from ij.process import ByteProcessor, ShortProcessor, FloatProcessor from java.io import RandomAccessFile
def open_Octopus_file(): # set up a file info structure fi = FileInfo() fi.fileFormat = fi.RAW fi.fileType=FileInfo.GRAY16_UNSIGNED fi.intelByteOrder = True fi.nImages = 1 op = OpenDialog("Choose Octopus .dth file...", "") if not op.getDirectory(): return False # get the file extension file_extension = re.search('(\.[a-z][a-z][a-z])', op.getFileName()).group(1) if file_extension != ".dth": dlg = GenericDialog("Warning") dlg.addMessage("Please select an octopus .dth file") dlg.showDialog() return False # now strip the filename into a stem and index file_parse = re.match('([a-zA-z0-9_]*_)([0-9]+)\.dth', op.getFileName()) file_stem = file_parse.group(1) file_index = int( file_parse.group(2) ) # ok now we need to parse the header info header = get_Octopus_header(op.getDirectory(), file_stem, file_index) fi.nImages = len(header['N']) # check to see whether we have a bit depth, if not, assume 16-bit if 'Bit_Depth' in header: print header['Bit_Depth'] bit_depth = int(header['Bit_Depth'][0]) if bit_depth == 8: fi.fileType = FileInfo.GRAY8 else: bit_depth = 16 # will assume that all files have the same size fi.width = int( header['W'][0] ) fi.height = int( header['H'][0] ) file_timestamp = strftime("%a, %d %b %Y %H:%M:%S", gmtime(float(header['Time'][0])) ) # make a new imagestack to store the data stack = ImageStack(fi.width, fi.height) # finally, we need to make a list of files to import as sometimes we have # non contiguous file numbers try: files = os.listdir(op.getDirectory()) except IOError: raise IOError( "No files exist in directory: " + op.getDirectory()) filenums = [] for f in files: # strip off the stem, and get the number targetfile = re.match(file_stem+'([0-9]+)\.dth', f) # only take thosefiles which match the formatting requirements if targetfile: filenums.append( int(targetfile.group(1)) ) # sort the file numbers sorted_filenums = sorted(filenums) # make a file stats string file_stats_str = file_stem + '\n' + str(fi.width) +'x' + str(fi.height) + 'x' + \ str(len(sorted_filenums)) +' ('+str(bit_depth)+'-bit)\n' + file_timestamp # now open a dialog to let the user set options dlg = GenericDialog("Load Octopus Stream (v"+__version__+")") dlg.addMessage(file_stats_str) dlg.addStringField("Title: ", file_stem) dlg.addNumericField("Start: ", 1, 0); dlg.addNumericField("End: ", len(sorted_filenums), 0) dlg.addCheckbox("Open headers", True) dlg.addCheckbox("Contiguous stream?", False) dlg.addCheckbox("8-bit unsigned", bit_depth==8) dlg.showDialog() # if we cancel the dialog, exit here if dlg.wasCanceled(): return # set some params file_title = dlg.getNextString() file_start = dlg.getNextNumber() file_end = dlg.getNextNumber() DISPLAY_HEADER = bool( dlg.getNextBoolean() ) # check the ranges if file_start > file_end: file_start, file_end = file_end, file_start if file_start < 1: file_start = 1 if file_end > len(sorted_filenums): file_end = len(sorted_filenums) # now set these to the actual file numbers in the stream file_start = sorted_filenums[int(file_start)-1] file_end = sorted_filenums[int(file_end)-1] files_to_open = [n for n in sorted_filenums if n>=file_start and n<=file_end] # if we've got too many, truncate the list if (len(files_to_open) * fi.nImages * fi.width * fi.height) > (MAX_FRAMES_TO_IMPORT*512*512): dlg = GenericDialog("Warning") dlg.addMessage("This may use a lot of memory. Continue?") dlg.showDialog() if dlg.wasCanceled(): return False IJ.log( "Opening file: " + op.getDirectory() + op.getFileName() ) IJ.log( file_stats_str + "\nFile range: " + str(files_to_open[0]) + \ "-" + str(files_to_open[-1]) +"\n" ) # make a results table for the metadata # NOTE: horrible looping at the moment, but works if DISPLAY_HEADER: rt = ResultsTable() # ok now we can put the files together into the stack for i in files_to_open: # open the original .dat file and get the stack fi.fileName = get_Octopus_filename( op.getDirectory(), file_stem, i) if os.path.isfile( fi.fileName ): fo = FileOpener(fi) imp = fo.open(False).getStack() # put the slices into the stack for im_slice in xrange( imp.getSize() ): ip = imp.getProcessor( im_slice+1 ) if bit_depth == 8: bi = ip.getBufferedImage() else: bi = ip.get16BitBufferedImage() stack.addSlice( file_title, ip ) if DISPLAY_HEADER: header = get_Octopus_header(op.getDirectory(), file_stem, i) for n in xrange(len(header['N'])): rt.incrementCounter() for k in header.keys(): rt.addValue(k, parse_header( header[k][n] ) ) else: break # done! output = ImagePlus('Octopus ('+file_stem+')', stack) output.show() if DISPLAY_HEADER: rt.show("Octopus header metadata") return True
metadataStr += addMetadataEntry('fileType', str(fileType)) metadataStr += addMetadataEntry('gapBetweenImages', str(gap+64)) if(metadataInconsistency > 0): metadataStr += addMetadataEntry('Inconsistent METADATA', str(metadataInconsistency)) metadataStr += endMetadata() metadataDlg = HTMLDialog("HIS parameters", metadataStr, 0) size = metadataDlg.getSize() if size.width < 300: size.width = 300 if size.height < 300: size.height = 300 metadataDlg.setSize(size) finfo = FileInfo() finfo.fileName = imp finfo.width = width finfo.height = height finfo.nImages = frames finfo.offset = offset+64 finfo.fileType = fileType-1 finfo.intelByteOrder = 1 finfo.gapBetweenImages = gap+64 finfo.fileFormat = 1 finfo.samplesPerPixel = 1 finfo.displayRanges = None finfo.lutSize = 0 finfo.whiteIsZero = 0 vs = VirtualStack() finfo.virtualStack = vs FileInfoVirtualStack(finfo)