def exportSegmentation(evt=None): display = Display.getFront() canvas = display.getCanvas() numLayer = display.getLayerSet().size(); exportMask(evt) files = [] for l in display.getLayerSet().getLayers(): for p in l.getDisplayables(Patch): files.append(p.getFilePath()) # Create virtual stack 'vs' vs = None for f in files: # if first image... if vs is None: imp = IJ.openImage(f) vs = VirtualStack(imp.width, imp.height, None, "/") vs.addSlice(f) ImagePlus("VSeg", vs).show() IJ.run("Duplicate...", "title=Segmentation duplicate range=1-30"); WindowManager.getImage("VSeg").close() ic = ImageCalculator() ic.run("Multiply stack", WindowManager.getImage("Segmentation"), WindowManager.getImage("Labels")); WindowManager.getImage("Labels").close()
def openStack(evt=None): display = Display.getFront() canvas = display.getCanvas() numLayer = display.getLayerSet().size(); files = [] for l in display.getLayerSet().getLayers(): for p in l.getDisplayables(Patch): files.append(p.getFilePath()) # Create virtual stack 'vs' vs = None for f in files: # if first image... if vs is None: imp = IJ.openImage(f) vs = VirtualStack(imp.width, imp.height, None, "/") vs.addSlice(f) layerset = display.getLayerSet() p = layerset.getProject() ImagePlus("VSeg", vs).show() IJ.run("Duplicate...", "title=" + p.getTitle() + " duplicate range=1-30"); WindowManager.getImage("VSeg").close() return p.getTitle()
def createMIP(self): print "starting createMIP" for a in self.itemSelected: ImStack = None for filename in self.dict1.get(a): self.savfileName = a if not filename.endswith(self.fileExt): continue path = self.sourceDir + filename # Upon finding the first image, initialize the VirtualStack if ImStack is None: imp = IJ.openImage(path) ImStack = VirtualStack(imp.width, imp.height, None, self.sourceDir) # Add a slice, relative to the sourceDIr ImStack.addSlice(filename) #adding text overlay to output images so we can differentiate them. Overlay is non destructive - does not affect pixel values of image, and can be selected and deleted prefix_overlay = Overlay() font = Font("SansSerif", Font.PLAIN, 10) roi = TextRoi(0, 0, a) roi.setStrokeColor(Color(1.00, 1.00, 1.00)) prefix_overlay.add(roi) # OnscreenImage = ImagePlus(self.sourceDir, ImStack) OnscreenImage.setOverlay(prefix_overlay) OnscreenImage.show() print "Generating MIP, waiting..." self.outimp = self.maxZprojection( OnscreenImage) #generate max projection self.outimp.setOverlay(prefix_overlay) self.outimp.show() print "Max projection generated" if self.saveState == "Y": self.saveMIP() print "Finished!"
def create_registered_hyperstack(imp, target_folder, channel): """ Takes the imp, which contains a virtual hyper stack, and determines the x,y,z drift for each pair of time points, using the preferred given channel, and output one image for each slide into the target folder.""" shifts = compute_frame_translations(imp, channel) # Make shifts relative to 0,0,0 of the original imp: shifts = concatenate_shifts(shifts) print "shifts concatenated:" for s in shifts: print s.x, s.y, s.z # Compute bounds of the new volume, # which accounts for all translations: minx, miny, minz, maxx, maxy, maxz = compute_min_max(shifts) # Make shifts relative to new canvas dimensions # so that the min values become 0,0,0 for shift in shifts: shift.x -= minx shift.y -= miny shift.z -= minz print "shifts relative to new dimensions:" for s in shifts: print s.x, s.y, s.z # new canvas dimensions: width = imp.width + maxx - minx height = maxy - miny + imp.height slices = maxz - minz + imp.getNSlices() print "New dimensions:", width, height, slices # Count number of digits of each dimension, to output zero-padded numbers: slice_digits = len(str(slices)) frame_digits = len(str(imp.getNFrames())) channel_digits = len(str(imp.getNChannels())) # List to accumulate all created names: names = [] # Prepare empty slice to pad in Z when necessary empty = imp.getProcessor().createProcessor(width, height) # if it's RGB, fill the empty slice with blackness if isinstance(empty, ColorProcessor): empty.setValue(0) empty.fill() # Write all slices to files: stack = imp.getStack() for frame in range(1, imp.getNFrames() + 1): shift = shifts[frame - 1] fr = "t" + zero_pad(frame, frame_digits) # Pad with mpty slices before reaching the first slice for s in range(shift.z): ss = "_z" + zero_pad(s + 1, slice_digits) # slices start at 1 for ch in range(1, imp.getNChannels() + 1): name = fr + ss + "_c" + zero_pad(ch, channel_digits) + ".tif" names.append(name) FileSaver(ImagePlus("", empty)).saveAsTiff(target_folder + "/" + name) # Add all proper slices for s in range(1, imp.getNSlices() + 1): ss = "_z" + zero_pad(s + shift.z, slice_digits) for ch in range(1, imp.getNChannels() + 1): ip = stack.getProcessor(imp.getStackIndex(ch, s, frame)) ip2 = ip.createProcessor(width, height) # potentially larger ip2.insert(ip, shift.x, shift.y) name = fr + ss + "_c" + zero_pad(ch, channel_digits) + ".tif" names.append(name) FileSaver(ImagePlus("", ip2)).saveAsTiff(target_folder + "/" + name) # Pad the end for s in range(shift.z + imp.getNSlices(), slices): ss = "_z" + zero_pad(s + 1, slice_digits) for ch in range(1, imp.getNChannels() + 1): name = fr + ss + "_c" + zero_pad(ch, channel_digits) + ".tif" names.append(name) FileSaver(ImagePlus("", empty)).saveAsTiff(target_folder + "/" + name) # Create virtual hyper stack with the result vs = VirtualStack(width, height, None, target_folder) for name in names: vs.addSlice(name) vs_imp = ImagePlus("registered time points", vs) vs_imp.setDimensions(imp.getNChannels(), len(names) / (imp.getNChannels() * imp.getNFrames()), imp.getNFrames()) vs_imp.setOpenAsHyperStack(True) IJ.log("\nHyperstack dimensions: time frames:" + str(vs_imp.getNFrames()) + ", slices: " + str(vs_imp.getNSlices()) + ", channels: " + str(vs_imp.getNChannels())) if 1 == vs_imp.getNSlices(): return vs_imp # Else, as composite mode = CompositeImage.COLOR if isinstance(imp, CompositeImage): mode = imp.getMode() else: return vs_imp return CompositeImage(vs_imp, mode)
def run(title): gd = GenericDialog("Record Window") gd.addMessage("Maximum number of frames to record.\nZero means infinite, interrupt with ESC key.") gd.addNumericField("Max. frames:", 50, 0) gd.addNumericField("Milisecond interval:", 300, 0) gd.addSlider("Start in (seconds):", 0, 20, 5) frames = [] titles = [] for f in Frame.getFrames(): if f.isEnabled() and f.isVisible(): frames.append(f) titles.append(f.getTitle()) gd.addChoice("Window:", titles, titles[0]) gd.addCheckbox("To file", False) gd.showDialog() if gd.wasCanceled(): return n_frames = int(gd.getNextNumber()) interval = gd.getNextNumber() / 1000.0 # in seconds frame = frames[gd.getNextChoiceIndex()] delay = int(gd.getNextNumber()) tofile = gd.getNextBoolean() dir = None if tofile: dc = DirectoryChooser("Directory to store image frames") dir = dc.getDirectory() if dir is None: return # dialog canceled snaps = [] borders = None executors = Executors.newFixedThreadPool(1) try: while delay > 0: IJ.showStatus("Starting in " + str(delay) + "s.") time.sleep(1) # one second delay -= 1 IJ.showStatus("Capturing frame borders...") bounds = frame.getBounds() robot = Robot() frame.toFront() time.sleep(0.5) # half a second borders = robot.createScreenCapture(bounds) IJ.showStatus("Recording " + frame.getTitle()) # Set box to the inside borders of the frame insets = frame.getInsets() box = bounds.clone() box.x = insets.left box.y = insets.top box.width -= insets.left + insets.right box.height -= insets.top + insets.bottom start = System.currentTimeMillis() / 1000.0 # in seconds last = start intervals = [] real_interval = 0 i = 1 fus = None if tofile: fus = [] # 0 n_frames means continuous acquisition while 0 == n_frames or (len(snaps) < n_frames and last - start < n_frames * interval): now = System.currentTimeMillis() / 1000.0 # in seconds real_interval = now - last if real_interval >= interval: last = now img = snapshot(frame, box) if tofile: fus.append(executors.submit(Saver(i, dir, bounds, borders, img, insets))) # will flush img i += 1 else: snaps.append(img) intervals.append(real_interval) else: time.sleep(interval / 5) # interrupt capturing: if IJ.escapePressed(): IJ.showStatus("Recording user-interrupted") break # debug: # print "insets:", insets # print "bounds:", bounds # print "box:", box # print "snap dimensions:", snaps[0].getWidth(), snaps[0].getHeight() # Create stack stack = None if tofile: for fu in snaps: fu.get() # wait on all stack = VirtualStack(bounds.width, bounds.height, None, dir) files = File(dir).list(TifFilter()) Arrays.sort(files) for f in files: stack.addSlice(f) else: stack = ImageStack(bounds.width, bounds.height, None) t = 0 for snap, real_interval in zip(snaps, intervals): bi = BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB) g = bi.createGraphics() g.drawImage(borders, 0, 0, None) g.drawImage(snap, insets.left, insets.top, None) stack.addSlice(str(IJ.d2s(t, 3)), ImagePlus("", bi).getProcessor()) t += real_interval snap.flush() bi.flush() borders.flush() ImagePlus(frame.getTitle() + " recording", stack).show() IJ.showStatus("Done recording " + frame.getTitle()) except Exception, e: print "Some error ocurred:" print e.printStackTrace() IJ.showStatus("") if borders is not None: borders.flush() for snap in snaps: snap.flush()
def run(title): gd = GenericDialog('Record Window') gd.addMessage( "Maximum number of frames to record.\nZero means infinite, interrupt with ESC key." ) gd.addNumericField('Max. frames:', 50, 0) gd.addNumericField('Milisecond interval:', 300, 0) gd.addSlider('Start in (seconds):', 0, 20, 5) frames = [] titles = [] for f in Frame.getFrames(): if f.isEnabled() and f.isVisible(): frames.append(f) titles.append(f.getTitle()) gd.addChoice('Window:', titles, titles[0]) gd.addCheckbox("To file", False) gd.showDialog() if gd.wasCanceled(): return n_frames = int(gd.getNextNumber()) interval = gd.getNextNumber() / 1000.0 # in seconds frame = frames[gd.getNextChoiceIndex()] delay = int(gd.getNextNumber()) tofile = gd.getNextBoolean() dir = None if tofile: dc = DirectoryChooser("Directory to store image frames") dir = dc.getDirectory() if dir is None: return # dialog canceled snaps = [] borders = None executors = Executors.newFixedThreadPool(1) try: while delay > 0: IJ.showStatus('Starting in ' + str(delay) + 's.') time.sleep(1) # one second delay -= 1 IJ.showStatus('Capturing frame borders...') bounds = frame.getBounds() robot = Robot() frame.toFront() time.sleep(0.5) # half a second borders = robot.createScreenCapture(bounds) IJ.showStatus("Recording " + frame.getTitle()) # Set box to the inside borders of the frame insets = frame.getInsets() box = bounds.clone() box.x = insets.left box.y = insets.top box.width -= insets.left + insets.right box.height -= insets.top + insets.bottom start = System.currentTimeMillis() / 1000.0 # in seconds last = start intervals = [] real_interval = 0 i = 1 fus = None if tofile: fus = [] # 0 n_frames means continuous acquisition while 0 == n_frames or (len(snaps) < n_frames and last - start < n_frames * interval): now = System.currentTimeMillis() / 1000.0 # in seconds real_interval = now - last if real_interval >= interval: last = now img = snapshot(frame, box) if tofile: fus.append( executors.submit( Saver(i, dir, bounds, borders, img, insets))) # will flush img i += 1 else: snaps.append(img) intervals.append(real_interval) else: time.sleep(interval / 5) # interrupt capturing: if IJ.escapePressed(): IJ.showStatus("Recording user-interrupted") break # debug: #print "insets:", insets #print "bounds:", bounds #print "box:", box #print "snap dimensions:", snaps[0].getWidth(), snaps[0].getHeight() # Create stack stack = None if tofile: for fu in snaps: fu.get() # wait on all stack = VirtualStack(bounds.width, bounds.height, None, dir) files = File(dir).list(TifFilter()) Arrays.sort(files) for f in files: stack.addSlice(f) else: stack = ImageStack(bounds.width, bounds.height, None) t = 0 for snap, real_interval in zip(snaps, intervals): bi = BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB) g = bi.createGraphics() g.drawImage(borders, 0, 0, None) g.drawImage(snap, insets.left, insets.top, None) stack.addSlice(str(IJ.d2s(t, 3)), ImagePlus('', bi).getProcessor()) t += real_interval snap.flush() bi.flush() borders.flush() ImagePlus(frame.getTitle() + " recording", stack).show() IJ.showStatus('Done recording ' + frame.getTitle()) except Exception, e: print "Some error ocurred:" print e.printStackTrace() IJ.showStatus('') if borders is not None: borders.flush() for snap in snaps: snap.flush()
def create_registered_hyperstack(imp, target_folder, channel): """ Takes the imp, which contains a virtual hyper stack, and determines the x,y,z drift for each pair of time points, using the preferred given channel, and output one image for each slide into the target folder.""" print "starting to calculate translations..." shifts = compute_frame_translations(imp, channel) # Make shifts relative to 0,0,0 of the original imp: shifts = concatenate_shifts(shifts) print "shifts concatenated:" for s in shifts: print s.x, s.y, s.z # Compute bounds of the new volume, # which accounts for all translations: minx, miny, minz, maxx, maxy, maxz = compute_min_max(shifts) # Make shifts relative to new canvas dimensions # so that the min values become 0,0,0 for shift in shifts: shift.x -= minx shift.y -= miny shift.z -= minz print "shifts relative to new dimensions:" for s in shifts: print s.x, s.y, s.z writer = CSVWriter(FileWriter(target_folder+"/shifts.csv"), ',') data = Array.newInstance(Class.forName("java.lang.String"), 3) for s in shifts: data[0] = str(s.x) data[1] = str(s.y) data[2] = str(s.z) writer.writeNext(data) writer.close() # new canvas dimensions: width = imp.width + maxx - minx height = maxy - miny + imp.height slices = maxz - minz + imp.getNSlices() print "New dimensions:", width, height, slices # Count number of digits of each dimension, to output zero-padded numbers: slice_digits = len(str(slices)) frame_digits = len(str(imp.getNFrames())) channel_digits = len(str(imp.getNChannels())) # List to accumulate all created names: names = [] # Prepare empty slice to pad in Z when necessary empty = imp.getProcessor().createProcessor(width, height) # if it's RGB, fill the empty slice with blackness if isinstance(empty, ColorProcessor): empty.setValue(0) empty.fill() # Write all slices to files: stack = imp.getStack() for frame in range(1, imp.getNFrames()+1): shift = shifts[frame-1] fr = "t" + zero_pad(frame, frame_digits) # Pad with mpty slices before reaching the first slice for s in range(shift.z): ss = "_z" + zero_pad(s + 1, slice_digits) # slices start at 1 for ch in range(1, imp.getNChannels()+1): name = fr + ss + "_c" + zero_pad(ch, channel_digits) +".tif" names.append(name) FileSaver(ImagePlus("", empty)).saveAsTiff(target_folder + "/" + name) # Add all proper slices for s in range(1, imp.getNSlices()+1): ss = "_z" + zero_pad(s + shift.z, slice_digits) for ch in range(1, imp.getNChannels()+1): ip = stack.getProcessor(imp.getStackIndex(ch, s, frame)) ip2 = ip.createProcessor(width, height) # potentially larger ip2.insert(ip, shift.x, shift.y) name = fr + ss + "_c" + zero_pad(ch, channel_digits) +".tif" names.append(name) FileSaver(ImagePlus("", ip2)).saveAsTiff(target_folder + "/" + name) # Pad the end for s in range(shift.z + imp.getNSlices(), slices): ss = "_z" + zero_pad(s + 1, slice_digits) for ch in range(1, imp.getNChannels()+1): name = fr + ss + "_c" + zero_pad(ch, channel_digits) +".tif" names.append(name) FileSaver(ImagePlus("", empty)).saveAsTiff(target_folder + "/" + name) # Create virtual hyper stack with the result vs = VirtualStack(width, height, None, target_folder) for name in names: vs.addSlice(name) vs_imp = ImagePlus("registered time points", vs) vs_imp.setDimensions(imp.getNChannels(), len(names) / (imp.getNChannels() * imp.getNFrames()), imp.getNFrames()) vs_imp.setOpenAsHyperStack(True) IJ.log("\nHyperstack dimensions: time frames:" + str(vs_imp.getNFrames()) + ", slices: " + str(vs_imp.getNSlices()) + ", channels: " + str(vs_imp.getNChannels())) if 1 == vs_imp.getNSlices(): return vs_imp # Else, as composite mode = CompositeImage.COLOR; if isinstance(imp, CompositeImage): mode = imp.getMode() else: return vs_imp return CompositeImage(vs_imp, mode)
test_virtual_stack_mac.py """ from ij import IJ, VirtualStack, ImagePlus import os git_home = os.getenv("GIT_HOME") img_dir = git_home + "/tips/ImageJ/py/test_virtual_stack/" print(img_dir) IJ.run("Close All") filtFiles = ["spheres-1.tif", "spheres-2.tif", "spheres-3.tif"] vs = None for f in filtFiles: if vs is None: path = img_dir + f imp = IJ.openImage(path) print(imp) imp.show() vs = VirtualStack(imp.width, imp.height, None, "/") vs.addSlice(path) else: path = img_dir + f vs.addSlice(path) imPlus = ImagePlus("Stack from subdirectories", vs) print imPlus imPlus.show()
def tiffImageFilenames(directory): for filename in sorted(os.listdir(directory)): if filename.lower().endswith(".tif"): yield filename # Read the dimensions from the first image first_path = os.path.join(sourceDir, tiffImageFilenames(sourceDir).next()) width, height = dimensionsOf(first_path) # Create the VirtualStack without a specific ColorModel # (which will be set much later upon loading any slice) vstack = VirtualStack(width, height, None, sourceDir) # Add all TIFF images in sourceDir as slices in vstack for filename in tiffImageFilenames(sourceDir): vstack.addSlice(filename) # Visualize the VirtualStack imp = ImagePlus("virtual stack of images in " + os.path.basename(sourceDir), vstack) # imp.show() from mpicbg.ij.plugin import NormalizeLocalContrast from ij.io import FileSaver # slice마다 process 후 targetDir에 save for i in xrange(0, vstack.size()): ip = vstack.getProcessor(i+1) # slice list는 1부터 시작 (1-based listing) # NormalizeLocalContrast plugin을 ImageProcessor에 적용 NormalizeLocalContrast.run(ip, 200, 200, 3, True, True) # 결과 저장 name = vstack.getFileName(i+1)
exit() # If you do not select a directory, terminates program # Assumes all files have the same size ImStack = None #print "os.walk: ", list(os.walk(sourceDir)) for root, directories, filenames in os.walk(sourceDir): for filename in filenames: # Skip non-TIFF files if not filename.endswith(".tif"): continue path = os.path.join(root, filename) # Upon finding the first image, initialize the VirtualStack if ImStack is None: imp = IJ.openImage(path) ImStack = VirtualStack(imp.width, imp.height, None, sourceDir) # Add a slice, relative to the sourceDIr ImStack.addSlice(path[len(sourceDir):]) OnscreenImage = ImagePlus(sourceDir, ImStack) OnscreenImage.show() print "Generating MIP, waiting..." outimp = maxZprojection(OnscreenImage) #generate max projection outimp.show() print "Max projection generated" ###To remove save functionality, just remove all beyond here- SaveQuery = JOptionPane.showInputDialog( None, "Would you like to save the max proj? y = save, anything else = don't save" )