示例#1
0
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()
示例#2
0
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()
示例#3
0
    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 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)
示例#5
0
def register_hyperstack_subpixel(imp, channel, shifts, target_folder, virtual):
  """ Takes the imp, determines the x,y,z drift for each pair of time points, using the preferred given channel,
  and outputs as a hyperstack.
  The shifted image is computed using TransformJ allowing for sub-pixel shifts using interpolation.
  This is quite a bit slower than just shifting the image by full pixels as done in above function register_hyperstack().
  However it significantly improves the result by removing pixel jitter.
  """
  # 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
  # new canvas dimensions:
  width = int(imp.width + maxx - minx)
  height = int(maxy - miny + imp.height)
  slices = int(maxz - minz + imp.getNSlices())

  #print "New dimensions:", width, height, slices
    
  # prepare stack for final results
  stack = imp.getStack()
  if virtual is True: 
    names = []
  else:
    registeredstack = ImageStack(width, height, imp.getProcessor().getColorModel())
  
  # prepare empty slice for padding
  empty = imp.getProcessor().createProcessor(width, height)

  IJ.showProgress(0)

  # get raw data as stack
  stack = imp.getStack()

  # loop across frames
  for frame in range(1, imp.getNFrames()+1):
      
    IJ.showProgress(frame / float(imp.getNFrames()+1))
    fr = "t" + zero_pad(frame, len(str(imp.getNFrames()))) # for saving files in a virtual stack
    
    # get and report current shift
    shift = shifts[frame-1]
    #print "frame",frame,"correcting drift",-shift.x-minx,-shift.y-miny,-shift.z-minz
    IJ.log("    frame "+str(frame)+" correcting drift "+str(round(-shift.x-minx,2))+","+str(round(-shift.y-miny,2))+","+str(round(-shift.z-minz,2)))

    # loop across channels
    for ch in range(1, imp.getNChannels()+1):      
      
      tmpstack = ImageStack(width, height, imp.getProcessor().getColorModel())

      # get all slices of this channel and frame
      for s in range(1, imp.getNSlices()+1):
        ip = stack.getProcessor(imp.getStackIndex(ch, s, frame))
        ip2 = ip.createProcessor(width, height) # potentially larger
        ip2.insert(ip, 0, 0)
        tmpstack.addSlice("", ip2)

      # Pad the end (in z) of this channel and frame
      for s in range(imp.getNSlices(), slices):
        tmpstack.addSlice("", empty)

      # subpixel translation
      imp_tmpstack = ImagePlus("", tmpstack)
      imp_translated = translate_single_stack_using_imglib2(imp_tmpstack, shift.x, shift.y, shift.z)
      
      # add translated stack to final time-series
      translated_stack = imp_translated.getStack()
      for s in range(1, translated_stack.getSize()+1):
        ss = "_z" + zero_pad(s, len(str(slices)))
        ip = translated_stack.getProcessor(s).duplicate() # duplicate is important as otherwise it will only be a reference that can change its content  
        if virtual is True:
          name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif"
          names.append(name)
          currentslice = ImagePlus("", ip)
          currentslice.setCalibration(imp.getCalibration().copy())
          currentslice.setProperty("Info", imp.getProperty("Info"));
          FileSaver(currentslice).saveAsTiff(target_folder + "/" + name)
        else:
          registeredstack.addSlice("", ip)    

  IJ.showProgress(1)
    
  if virtual is True:
    # Create virtual hyper stack
    registeredstack = VirtualStack(width, height, None, target_folder)
    for name in names:
      registeredstack.addSlice(name)
  
  registeredstack_imp = ImagePlus("registered time points", registeredstack)
  registeredstack_imp.setCalibration(imp.getCalibration().copy())
  registeredstack_imp.setProperty("Info", imp.getProperty("Info"))
  registeredstack_imp = HyperStackConverter.toHyperStack(registeredstack_imp, imp.getNChannels(), slices, imp.getNFrames(), "xyzct", "Composite");    
  
  return registeredstack_imp
示例#6
0
def register_hyperstack(imp, shifts, target_folder, virtual):
  """ Applies the shifts to all channels in the hyperstack."""
  # 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:r
  width = imp.width + maxx - minx
  height = maxy - miny + imp.height
  slices = maxz - minz + imp.getNSlices()

  print "New dimensions:", width, height, slices
  # 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()

  if virtual is False:
  	registeredstack = ImageStack(width, height, imp.getProcessor().getColorModel())
  names = []
  
  for frame in range(1, imp.getNFrames()+1):
 
    shift = shifts[frame-1]
    
    #print "frame",frame,"correcting drift",-shift.x-minx,-shift.y-miny,-shift.z-minz
    IJ.log("    frame "+str(frame)+" correcting drift "+str(-shift.x-minx)+","+str(-shift.y-miny)+","+str(-shift.z-minz))
    
    fr = "t" + zero_pad(frame, len(str(imp.getNFrames())))
    # Pad with empty slices before reaching the first slice
    for s in range(shift.z):
      ss = "_z" + zero_pad(s + 1, len(str(slices))) # slices start at 1
      for ch in range(1, imp.getNChannels()+1):
        name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif"
        names.append(name)

        if virtual is True:
          currentslice = ImagePlus("", empty)
          currentslice.setCalibration(imp.getCalibration().copy())
          currentslice.setProperty("Info", imp.getProperty("Info"))
          FileSaver(currentslice).saveAsTiff(target_folder + "/" + name)
        else:
          empty = imp.getProcessor().createProcessor(width, height)
          registeredstack.addSlice(str(name), empty)
    
    
    # Add all proper slices
    stack = imp.getStack()
    for s in range(1, imp.getNSlices()+1):
      ss = "_z" + zero_pad(s + shift.z, len(str(slices)))
      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, len(str(imp.getNChannels()))) +".tif"
         names.append(name)

         if virtual is True:
           currentslice = ImagePlus("", ip2)
           currentslice.setCalibration(imp.getCalibration().copy())
           currentslice.setProperty("Info", imp.getProperty("Info"));
           FileSaver(currentslice).saveAsTiff(target_folder + "/" + name)
         else:
           registeredstack.addSlice(str(name), ip2)

    # Pad the end
    for s in range(shift.z + imp.getNSlices(), slices):
      ss = "_z" + zero_pad(s + 1, len(str(slices)))
      for ch in range(1, imp.getNChannels()+1):
        name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif"
        names.append(name)

        if virtual is True:
          currentslice = ImagePlus("", empty)
          currentslice.setCalibration(imp.getCalibration().copy())
          currentslice.setProperty("Info", imp.getProperty("Info"))
          FileSaver(currentslice).saveAsTiff(target_folder + "/" + name)
        else:
          registeredstack.addSlice(str(name), empty)
 
  if virtual is True:
    # Create virtual hyper stack
    registeredstack = VirtualStack(width, height, None, target_folder)
    for name in names:
      registeredstack.addSlice(name)
  
  registeredstack_imp = ImagePlus("registered time points", registeredstack)
  registeredstack_imp.setCalibration(imp.getCalibration().copy())
  registeredstack_imp.setProperty("Info", imp.getProperty("Info"))
  registeredstack_imp = HyperStackConverter.toHyperStack(registeredstack_imp, imp.getNChannels(), len(names) / (imp.getNChannels() * imp.getNFrames()), imp.getNFrames(), "xyczt", "Composite");    
  
  return registeredstack_imp
示例#7
0
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)
示例#8
0
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()
示例#9
0
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 register_hyperstack_subpixel(imp, channel, shifts, target_folder, virtual):
  """ Takes the imp, determines the x,y,z drift for each pair of time points, using the preferred given channel,
  and outputs as a hyperstack.
  The shifted image is computed using TransformJ allowing for sub-pixel shifts using interpolation.
  This is quite a bit slower than just shifting the image by full pixels as done in above function register_hyperstack().
  However it significantly improves the result by removing pixel jitter.
  """
  # 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
  # new canvas dimensions:
  width = int(imp.width + maxx - minx)
  height = int(maxy - miny + imp.height)
  slices = int(maxz - minz + imp.getNSlices())

  print "New dimensions:", width, height, slices
  
  # prepare stack for final results
  stack = imp.getStack()
  if virtual is True: 
    names = []
  else:
    registeredstack = ImageStack(width, height, imp.getProcessor().getColorModel())
  
  # prepare empty slice for padding
  empty = imp.getProcessor().createProcessor(width, height)

  IJ.showProgress(0)
  
  for frame in range(1, imp.getNFrames()+1):
      
    IJ.showProgress(frame / float(imp.getNFrames()+1))
    fr = "t" + zero_pad(frame, len(str(imp.getNFrames()))) # for saving files in a virtual stack
    
    # init
    shift = shifts[frame-1]
    tmpstack = ImageStack(width, height, imp.getProcessor().getColorModel())

    print "frame",frame,"correcting drift",-shift.x-minx,-shift.y-miny,-shift.z-minz
    IJ.log("    frame "+str(frame)+" correcting drift "+str(round(-shift.x-minx,2))+","+str(round(-shift.y-miny,2))+","+str(round(-shift.z-minz,2)))

    # for doing the same with imglib2 i would have to put the channel loop 
    # to the outside and translate each individual channel as long as i don't figure out 
    # to two wrap a composite imglib2 image into an imp
        
    # Add all slices of this frame
    stack = imp.getStack()
    for s in range(1, imp.getNSlices()+1):
      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, 0, 0)
         tmpstack.addSlice("", ip2)

    # Pad the end (in z) of this frame
    for s in range(imp.getNSlices(), slices):
      for ch in range(1, imp.getNChannels()+1):
         tmpstack.addSlice("", empty)

    # Set correct dimensions of this frame 
    # ..it is important *not* to set the calibration as translation should be in pixels units
    imp_tmpstack = ImagePlus("registered time points", tmpstack)
    imp_tmpstack.setProperty("Info", imp.getProperty("Info"))
    imp_tmpstack.setDimensions(imp.getNChannels(), slices, 1)
    imp_tmpstack.setOpenAsHyperStack(True)
    
    # subpixel translation
    imp_translated = translate_using_imagescience(imp_tmpstack, shift.x, shift.y, shift.z)
    #imp_translated = translate_using_imglib2(imp_tmpstack, shift.x, shift.y, shift.z)
    
    imp_translated.setProperty("Info", imp.getProperty("Info"))
    imp_translated.setDimensions(imp.getNChannels(), slices, 1)
    imp_translated.setOpenAsHyperStack(True)

    # Add translated frame to final time-series
    stack = imp_translated.getStack()
    for s in range(1, imp_translated.getNSlices()+1):
      ss = "_z" + zero_pad(s, len(str(slices)))
      for ch in range(1, imp_translated.getNChannels()+1):
         ip = stack.getProcessor(imp_translated.getStackIndex(ch, s, 1))
         if virtual is True:
           name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif"
           names.append(name)
           currentslice = ImagePlus("", ip)
           currentslice.setCalibration(imp.getCalibration().copy())
           currentslice.setProperty("Info", imp.getProperty("Info"));
           FileSaver(currentslice).saveAsTiff(target_folder + "/" + name)
         else:
           registeredstack.addSlice("", ip)
  
  IJ.showProgress(1)

  if virtual is True:
    # Create virtual hyper stack with the result
    registeredstack = VirtualStack(width, height, None, target_folder)
    for name in names:
      registeredstack.addSlice(name)
    registeredstack_imp = ImagePlus("registered time points", registeredstack)
    registeredstack_imp.setDimensions(imp.getNChannels(), slices, imp.getNFrames())
    registeredstack_imp.setCalibration(imp.getCalibration().copy())
    registeredstack_imp.setOpenAsHyperStack(True)
  else:
    registeredstack_imp = ImagePlus("registered time points", registeredstack)
    registeredstack_imp.setCalibration(imp.getCalibration().copy())
    registeredstack_imp.setProperty("Info", imp.getProperty("Info"))
    registeredstack_imp.setDimensions(imp.getNChannels(), slices, imp.getNFrames())
    registeredstack_imp.setOpenAsHyperStack(True)
    if 1 == registeredstack_imp.getNChannels():
      return registeredstack_imp
     
  #IJ.log("\nHyperstack dimensions: time frames:" + str(registeredstack_imp.getNFrames()) + ", slices: " + str(registeredstack_imp.getNSlices()) + ", channels: " + str(registeredstack_imp.getNChannels()))

  # Else, as composite
  mode = CompositeImage.COLOR;
  if isinstance(imp, CompositeImage):
    mode = imp.getMode()
  else:
    return registeredstack_imp
  return CompositeImage(registeredstack_imp, mode)
示例#11
0
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)
示例#12
0
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()
    finally:
        fr.close()

# A generator over all file paths in sourceDir
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)
示例#14
0
if not sourceDir:
    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,
示例#15
0
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)
示例#16
0
def create_registered_hyperstack(imp, channel, target_folder, virtual):
  """ Takes the imp, determines the x,y,z drift for each pair of time points, using the preferred given channel,
  and outputs as a hyperstack."""
  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
  # 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()

  if virtual is False:
  	registeredstack = ImageStack(width, height, imp.getProcessor().getColorModel())
  names = []
  for frame in range(1, imp.getNFrames()+1):
    shift = shifts[frame-1]
    fr = "t" + zero_pad(frame, len(str(imp.getNFrames())))
    # Pad with empty slices before reaching the first slice
    for s in range(shift.z):
      ss = "_z" + zero_pad(s + 1, len(str(slices))) # slices start at 1
      for ch in range(1, imp.getNChannels()+1):
        name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif"
        names.append(name)

        if virtual is True:
          currentslice = ImagePlus("", empty)
          currentslice.setCalibration(imp.getCalibration().copy())
          currentslice.setProperty("Info", imp.getProperty("Info"))
          FileSaver(currentslice).saveAsTiff(target_folder + "/" + name)
        else:
          empty = imp.getProcessor().createProcessor(width, height)
          registeredstack.addSlice(str(name), empty)
    # Add all proper slices
    stack = imp.getStack()
    for s in range(1, imp.getNSlices()+1):
      ss = "_z" + zero_pad(s + shift.z, len(str(slices)))
      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, len(str(imp.getNChannels()))) +".tif"
         names.append(name)

         if virtual is True:
           currentslice = ImagePlus("", ip2)
           currentslice.setCalibration(imp.getCalibration().copy())
           currentslice.setProperty("Info", imp.getProperty("Info"));
           FileSaver(currentslice).saveAsTiff(target_folder + "/" + name)
         else:
           registeredstack.addSlice(str(name), ip2)

    # Pad the end
    for s in range(shift.z + imp.getNSlices(), slices):
      ss = "_z" + zero_pad(s + 1, len(str(slices)))
      for ch in range(1, imp.getNChannels()+1):
        name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif"
        names.append(name)

        if virtual is True:
          currentslice = ImagePlus("", empty)
          currentslice.setCalibration(imp.getCalibration().copy())
          currentslice.setProperty("Info", imp.getProperty("Info"))
          FileSaver(currentslice).saveAsTiff(target_folder + "/" + name)
        else:
          registeredstack.addSlice(str(name), empty)

  if virtual is True:
      # Create virtual hyper stack with the result
      registeredstack = VirtualStack(width, height, None, target_folder)
      for name in names:
        registeredstack.addSlice(name)
      registeredstack_imp = ImagePlus("registered time points", registeredstack)
      registeredstack_imp.setDimensions(imp.getNChannels(), len(names) / (imp.getNChannels() * imp.getNFrames()), imp.getNFrames())
      registeredstack_imp.setCalibration(imp.getCalibration().copy())
      registeredstack_imp.setOpenAsHyperStack(True)

  else:
    registeredstack_imp = ImagePlus("registered time points", registeredstack)
    registeredstack_imp.setCalibration(imp.getCalibration().copy())
    registeredstack_imp.setProperty("Info", imp.getProperty("Info"))
    registeredstack_imp.setDimensions(imp.getNChannels(), len(names) / (imp.getNChannels() * imp.getNFrames()), imp.getNFrames())
    registeredstack_imp.setOpenAsHyperStack(True)
    if 1 == registeredstack_imp.getNChannels():
      return registeredstack_imp
  IJ.log("\nHyperstack dimensions: time frames:" + str(registeredstack_imp.getNFrames()) + ", slices: " + str(registeredstack_imp.getNSlices()) + ", channels: " + str(registeredstack_imp.getNChannels()))

  # Else, as composite
  mode = CompositeImage.COLOR;
  if isinstance(imp, CompositeImage):
    mode = imp.getMode()
  else:
    return registeredstack_imp
  return CompositeImage(registeredstack_imp, mode)
示例#17
0
        return fr.getSizeX(), fr.getSizeY()
    except:
        # 에러 발생시 출력
        print sys_exc_info()
    finally:
        fr.close()


# A generator over all file paths in sourceDir
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()