def run(): srcDir = DirectoryChooser("Choose!").getDirectory() if not srcDir: # user canceled dialog return # Assumes all files have the same size filepaths = [] pattern = re.compile('ch1(.*)_(.*)transformed.mha') for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Skip non-TIFF files match = re.search(pattern, filename) if (match == None) or (match.group(1) == None): continue print(filename) path = os.path.join(root, filename) filepaths.append(path) # Upon finding the first image, initialize the VirtualStack vs = None sorted_filepaths = sorted(filepaths) for f in sorted(filepaths): IJ.openImage(f) print(f.split('\\')[-1]) imp = IJ.getImage() if vs is None: vs = ImageStack(imp.width, imp.height) # Add a slice, relative to the srcDir vs.addSlice(f.split('\\')[-1],imp.getProcessor()) imp.hide() ImagePlus("Stack from subdirectories", vs).show()
def reslice(image, pixelDepth): w = image.getWidth() h = image.getHeight() cal = image.getCalibration() stack = image.getStack() numSlices = int(round(image.getStackSize() * cal.pixelDepth / pixelDepth)) newStack = ImageStack(w, h) for z in range(numSlices): currentPos = z * pixelDepth ind_p = int(currentPos / cal.pixelDepth) ind_n = ind_p + 1 d_p = currentPos - ind_p * cal.pixelDepth d_n = ind_n * cal.pixelDepth - currentPos if ind_n >= stack.getSize(): ind_n = stack.getSize() - 1 before = stack.getProcessor(ind_p + 1).duplicate() after = stack.getProcessor(ind_n + 1).duplicate() before.multiply(d_n / (d_n + d_p)) after.multiply(d_p / (d_n + d_p)) before.copyBits(after, 0, 0, Blitter.ADD) newStack.addSlice("", before) result = ImagePlus("Resliced", newStack) cal = cal.copy() cal.pixelDepth = pixelDepth result.setCalibration(cal) return result
def run(): sId = IJ.getString("Filenames contain:", "T0000"); srcDir = DirectoryChooser("Choose!").getDirectory() if not srcDir: # user canceled dialog return # Assumes all files have the same size stack = None for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Skip non-TIFF files if not (sId in filename): continue print(filename) path = os.path.join(root, filename) # Upon finding the first image, initialize the VirtualStack imp = IJ.openImage(path) if stack is None: # stack = VirtualStack(imp.width, imp.height, None, srcDir) stack = ImageStack(imp.width, imp.height) # Add a slice to the virtual stack, relative to the srcDir # #stack.addSlice(path[len(srcDir):]) # Add a slice to the real stack # stack.addSlice(filename, imp.getProcessor()) # Make a ImagePlus from the stack ImagePlus("Stack from subdirectories", stack).show()
def z_stack_opener(path, numberOfSlices="1", file_name_string="%s-Site_%s_%s_z%s.tif", file_name_variables=[]): """ Opens a series of tifs into a stack. args: path -- path to files numberOfSlices -- the number of slices to open min 1 file_name_string -- string with %s formating spaces, z must be last file_name_variables -- list of variables to fill in %s spaces returns: z_stack -- imageJ stack -- stack of processors paths -- list of paths to the files that were opened """ paths = [] full_file_name_string = os.path.join(path, file_name_string) ## open the first slice all_name_variables = tuple(file_name_variables + ["1"]) img = IJ.openImage(full_file_name_string % all_name_variables) ## open a stack z_stack = ImageStack(img.width, img.height) z_stack.addSlice(file_name_string % all_name_variables, img.getProcessor()) paths.append(full_file_name_string % all_name_variables) ## open the other slices for i in range(2, numberOfSlices + 1): sliceNameVariables = tuple(file_name_variables + [str(i)]) img = IJ.openImage(full_file_name_string % sliceNameVariables) z_stack.addSlice(file_name_string % sliceNameVariables, img.getProcessor()) paths.append(full_file_name_string % sliceNameVariables) return z_stack, paths
def getCroppedChannels(self, imp, cell): splitter = ChannelSplitter() imp.setRoi(None) if cell.mode3D: cropRoi = cell.getCropRoi() else: cropRoi = cell.roi if cropRoi is None: return None crop = cropRoi.getBounds() channels = [] for c in range(1, imp.getNChannels() + 1): slices = ImageStack(crop.width, crop.height) channel = splitter.getChannel(imp, c) for z in range(1, channel.getSize() + 1): zslice = channel.getProcessor(z) zslice.setRoi(cropRoi) nslice = zslice.crop() if cell.mode3D: oroi = cell.slices[z - 1].roi else: oroi = cell.roi if oroi is not None: roi = oroi.clone() bounds = roi.getBounds() roi.setLocation(bounds.x - crop.x, bounds.y - crop.y) nslice.setColor(Color.black) nslice.fillOutside(roi) slices.addSlice(nslice) channels.append(ImagePlus("Channel %i" % c, slices)) return channels
def outline(imp3, originalTitle): #clij implementation """ src=clij2.push(imp3) dst=clij2.create(src) dst2=clij2.create(src) clij2.detectLabelEdges(src,dst) clij2.binaryNot(dst,dst2) clij2.multiplyImages(src, dst2, dst) imp4=clij2.pull(dst) imp4.show() clij2.clear() """ imp2 = imp3.duplicate() stack1 = imp3.getStack() width = imp3.getWidth() height = imp3.getHeight() stack2 = ImageStack(width, height) pixlist = [] for i in range(imp3.getNSlices()): pixlist = [] pixels1 = stack1.getPixels(i + 1) #if pixel is different to the pixel to the left or above, set it to 0 pixels2 = map( lambda j: pixels1[j] if pixels1[j] - pixels1[j - 1] == 0 and pixels1[j] - pixels1[j - width] == 0 else 0, xrange(len(pixels1))) processor = FloatProcessor(width, height, pixels2, None) stack2.addSlice(processor) imp2 = ImagePlus("Nearest point emission ratios of " + originalTitle, stack2) imp2.show() return imp2
def run(): sId = IJ.getString("Filenames contain:", "T0000") srcDir = DirectoryChooser("Choose!").getDirectory() if not srcDir: # user canceled dialog return # Assumes all files have the same size stack = None for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Skip non-TIFF files if not (sId in filename): continue print(filename) path = os.path.join(root, filename) # Upon finding the first image, initialize the VirtualStack imp = IJ.openImage(path) if stack is None: # stack = VirtualStack(imp.width, imp.height, None, srcDir) stack = ImageStack(imp.width, imp.height) # Add a slice to the virtual stack, relative to the srcDir # #stack.addSlice(path[len(srcDir):]) # Add a slice to the real stack # stack.addSlice(filename, imp.getProcessor()) # Make a ImagePlus from the stack ImagePlus("Stack from subdirectories", stack).show()
def images_to_frames_stack(imgdir, savestack=False): ''' Method for preparing a stack of frames using images inside the input folder. When savestack is true it saves the resulting stack to the images folder while opening the stack. ''' title = "tracing_stack.tiff" # Title of the final image stack. imgdir = imgdir.getPath() imglist = buildList(imgdir, ext) if not imglist: raise IOError("No {0} were found in {0}.".format(ext, imgdir)) method = "max" implist = [] for img in imglist: imp = ImagePlus(img) if imp.isStack(): imp = ZProjector.run(imp, method) implist.append(imp) stack = ImageStack( implist[0].getWidth(), implist[0].getHeight()) [stack.addSlice(img.getProcessor()) for img in implist] stackimp = ImagePlus(title, stack) IJ.run(stackimp, "Properties...", "slices=1 frames={0}".format(stackimp.getStackSize())) if savestack: IJ.log("# Saving tracing stack...") save_string = os.path.join(imgdir, title) fs = ThreadedFileSaver.ThreadedFileSaver(stackimp, save_string, "saveAsTiff") fs.start() stackimp.show()
def threshold(imPlus, edgeThreshold=2500): mask = Duplicator().run(imPlus) mask_stk = mask.getStack() # First, we threshold based on edges IJ.setThreshold(mask, edgeThreshold, 100000, "No Update") for i in range(mask.getImageStackSize()): mask_stk.getProcessor(i + 1).findEdges() IJ.run(mask, "Make Binary", "method=Default background=Default black") # Now, we need to clean up the binary images morphologically IJ.run(mask, "Dilate", "stack") IJ.run(mask, "Fill Holes", "stack") IJ.run(mask, "Erode", "stack") IJ.run(mask, "Erode", "stack") # Finally, remove the small particles stk = ImageStack(mask.getWidth(), mask.getHeight()) p = PA(PA.SHOW_MASKS, 0, None, 200, 100000) p.setHideOutputImage(True) for i in range(mask_stk.getSize()): mask.setSliceWithoutUpdate(i + 1) p.analyze(mask) mmap = p.getOutputImage() stk.addSlice(mmap.getProcessor()) mask.setStack(stk) mask.setSliceWithoutUpdate(1) mask.setTitle(mask_title(imPlus.getTitle())) mask.show() return mask
def segmentNuc(impc2): impdup = Duplicator().run(impc2) IJ.run(impdup, "8-bit", "") IJ.run(impdup, "Gaussian Blur...", "sigma=1.5 stack") # AutoThresholder().getThreshold(AutoThresholder.Method.valuOf('Otsu'), int[] histogram) IJ.setAutoThreshold(impdup, "Otsu dark") IJ.run(impdup, "Convert to Mask", "stack") #IJ.setAutoThreshold(impdup, "Otsu dark") #opt = PA.SHOW_MASKS + PA.SHOW_RESULTS + PA.EXCLUDE_EDGE_PARTICLES + PA.INCLUDE_HOLES # option for stack missing opt = PA.SHOW_MASKS + PA.EXCLUDE_EDGE_PARTICLES + PA.INCLUDE_HOLES # option for stack missing ##area mean centroid bounding integrated stack redirect=None decimal=4 meas = Meas.AREA + Meas.MEAN + Meas.CENTROID + Meas.RECT + Meas.INTEGRATED_DENSITY + Meas.STACK_POSITION rt = ResultsTable().getResultsTable() pa = PA(opt, meas, rt, 10.0, 300000.0, 0, 1.0) PA.processStack = True pa.setHideOutputImage(True) ##run("Analyze Particles...", "size=800-Infinity circularity=0.00-1.00 pixel show=Masks display exclude include stack"); outstack = ImageStack(impdup.getWidth(), impdup.getHeight()) for i in range(1,impdup.getStackSize()+1): impdup.setSlice(i) pa.analyze(impdup) impbin = pa.getOutputImage() outstack.addSlice(impbin.getProcessor()) impbin = ImagePlus("out", outstack) IJ.run(impbin, "Invert LUT", "") #IJ.run(impbin, "Fill Holes", "stack") return impbin, rt
def thresholdStackW(imp, low, high): i = 1 stack = imp.getStack() depth = imp.getNSlices() print "thresholdStackW: depth", depth width = stack.getProcessor(i).getWidth() height = stack.getProcessor(i).getHeight() winput = [None] w = Weaver.inline( """ byte[] input = (byte[]) winput.get(0); byte[] output = new byte[input.length]; for (int i=0; i<input.length; i++) { if (input[i] < low || input[i] > high){ output[i] = (byte)0; } else { output[i] = (byte)255; } } return output; """, {"winput":winput, "low":low, "high":high}) stackout = ImageStack(width, height) for k in range(1, depth+1): ip = stack.getProcessor(k) winput[0] = ip.getPixels() pixels = w.call() ipout = ByteProcessor(width, height) ipout.setPixels(pixels) stackout.addSlice(ipout) imp.setStack(stackout)
def GlidingSubtracter(imp): name = imp.getTitle() width, height, nChannels, nSlices, nFrames = imp.getDimensions() IJ.log("nFrames: {}".format(nFrames)) # Catch wrong input dimensions. if nChannels != 1: IJ.log("GlidingSubtracter only takes single channel images.") return None if nFrames <= 1: IJ.log("Stack has <= 1 frame. Perhaps switch Frames and Slices?") return None instack = imp.getImageStack() outstack = ImageStack() frame1 = instack.getProcessor(1) frame1 = ImagePlus("frame1", frame1) for i in range(1, nFrames): frame2 = instack.getProcessor(i) frame2 = ImagePlus("frame2", frame2) subtracted = ImageCalculator().run("subtract create 32-bit", frame1, frame2).getProcessor() # ImagePlus("slice", subtracted).show() outstack.addSlice(subtracted) outname = "subtract-" + name outstack = ImagePlus(outname, outstack) return outstack
def extractChannel(imp, nChannel, nFrame): """ Extract a stack for a specific color channel and time frame """ stack = imp.getImageStack() ch = ImageStack(imp.width, imp.height) for i in range(1, imp.getNSlices() + 1): index = imp.getStackIndex(nChannel, i, nFrame) ch.addSlice(str(i), stack.getProcessor(index)) return ImagePlus("Channel " + str(nChannel), ch)
def extractChannel(imp, nChannel, nChannels): """ Extract a stack for a specific color channel """ stack = imp.getImageStack() ch = ImageStack(imp.width, imp.height) for i in range(1, imp.getNSlices() + 1): index = (i - 1) * nChannels + nChannel ch.addSlice(str(i), stack.getProcessor(index)) return ImagePlus("Channel " + str(nChannel), ch)
def stack_from_list_of_imp(list_of_imps): ''' Returns an ImageStack that contains the images of the given list. :param list_of_imp: A list of ImagePlus objects. ''' stack = ImageStack(list_of_imps[0].getWidth(), list_of_imps[0].getHeight()) for img in list_of_imps: stack.addSlice(img.getTitle(), img.getProcessor()) return stack
def extract_stack_under_arealist(): # Check that a Display is open display = Display.getFront() if display is None: IJ.log("Open a TrakEM2 Display first!") return # Check that an AreaList is selected and active: ali = display.getActive() if ali is None or not isinstance(ali, AreaList): IJ.log("Please select an AreaList first!") return # Get the range of layers to which ali paints: ls = display.getLayerSet() ifirst = ls.indexOf(ali.getFirstLayer()) ilast = ls.indexOf(ali.getLastLayer()) layers = display.getLayerSet().getLayers().subList(ifirst, ilast +1) # Create a stack with the dimensions of ali bounds = ali.getBoundingBox() stack = ImageStack(bounds.width, bounds.height) # Using 16-bit. To change to 8-bit, use GRAY8 and ByteProcessor in the two lines below: type = ImagePlus.GRAY16 ref_ip = ShortProcessor(bounds.width, bounds.height) for layer in layers: area = ali.getArea(layer) z = layer.getZ() ip = ref_ip.createProcessor(bounds.width, bounds.height) if area is None: stack.addSlice(str(z), bp) continue # Create a ROI from the area of ali at layer: aff = ali.getAffineTransformCopy() aff.translate(-bounds.x, -bounds.y) roi = ShapeRoi(area.createTransformedArea(aff)) # Create a cropped snapshot of the images at layer under ali: flat = Patch.makeFlatImage(type, layer, bounds, 1.0, layer.getDisplayables(Patch), Color.black) b = roi.getBounds() flat.setRoi(roi) ip.insert(flat.crop(), b.x, b.y) # Clear the outside of ROI (ShapeRoi is a non-rectangular ROI type) bimp = ImagePlus("", ip) bimp.setRoi(roi) ip.setValue(0) ip.setBackgroundValue(0) IJ.run(bimp, "Clear Outside", "") # Accumulate slices stack.addSlice(str(z), ip) imp = ImagePlus("AreaList stack", stack) imp.setCalibration(ls.getCalibrationCopy()) imp.show()
def extractFrames(imp, interval, offset, nFrames): """ Extract a stack containing a subset of frames from a stack """ stack = imp.getImageStack() man = ImageStack(imp.width, imp.height) for i in range(0, nFrames): index = imp.getStackIndex(0, 1, i * interval + offset) man.addSlice(stack.getProcessor(index)) return ImagePlus("Manual_" + filename, man)
def analyzeParticles(imp, minsize, maxsize, mincirc, maxcirc, filename='Test.czi', addROIManager=True, headless=True, exclude=True): if addROIManager is True: if exclude is False: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_MANAGER \ + PA.ADD_TO_OVERLAY \ if exclude is True: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_MANAGER \ + PA.ADD_TO_OVERLAY \ + PA.EXCLUDE_EDGE_PARTICLES if addROIManager is False: if exclude is False: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_OVERLAY \ if exclude is True: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_OVERLAY \ + PA.EXCLUDE_EDGE_PARTICLES measurements = PA.STACK_POSITION \ + PA.LABELS \ + PA.AREA \ + PA.RECT \ results = ResultsTable() p = PA(options, measurements, results, minsize, maxsize, mincirc, maxcirc) p.setHideOutputImage(True) particlestack = ImageStack(imp.getWidth(), imp.getHeight()) for i in range(imp.getStackSize()): imp.setSliceWithoutUpdate(i + 1) ip = imp.getProcessor() #IJ.run(imp, "Convert to Mask", "") p.analyze(imp, ip) mmap = p.getOutputImage() particlestack.addSlice(mmap.getProcessor()) return particlestack, results
def run(title): gd = GenericDialog('Record Desktop') gd.addNumericField('Max. frames:', 50, 0) gd.addNumericField('Milisecond interval:', 300, 0) gd.addSlider('Start in (seconds):', 0, 20, 5) gd.showDialog() if gd.wasCanceled(): return n_frames = int(gd.getNextNumber()) interval = gd.getNextNumber() / 1000.0 # in seconds delay = int(gd.getNextNumber()) snaps = [] try: while delay > 0: IJ.showStatus('Starting in ' + str(delay) + 's.') time.sleep(1) # one second delay -= 1 IJ.showStatus('') System.out.println("Starting...") # start capturing robot = Robot() box = Rectangle(IJ.getScreenSize()) start = System.currentTimeMillis() / 1000.0 # in seconds last = start intervals = [] real_interval = 0 # Initial shot snaps.append(robot.createScreenCapture(box)) while 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 snaps.append(robot.createScreenCapture(box)) intervals.append(real_interval) else: time.sleep(interval / 5) # time in seconds # Create stack System.out.println("End") awt = snaps[0] stack = ImageStack(awt.getWidth(None), awt.getHeight(None), None) t = 0 for snap, real_interval in zip(snaps, intervals): stack.addSlice(str(IJ.d2s(t, 3)), ImagePlus('', snap).getProcessor()) snap.flush() t += real_interval ImagePlus("Desktop recording", stack).show() except Exception, e: print "Some error ocurred:" print e for snap in snaps: snap.flush()
def assembleChannelImagesInStacks(imageTitle, arrayOfImages, valeurSelectionDisplayMode, valeurSelectionTypeFichier): maxNumberOfChannels = len(arrayOfImages) maxNumberOfZDepth = 1; maxNumberOfTimeStamps = 1; print("assembleChannelImagesInStacks - arrayOfImages: "+str(arrayOfImages)) for channelNumber in range(len(arrayOfImages)): if valeurSelectionTypeFichier == "1 fichier par canal (NOM_FICHIER_chXX.tif)": numberOfZDepth = len(arrayOfImages[channelNumber]) if numberOfZDepth > maxNumberOfZDepth: maxNumberOfZDepth = numberOfZDepth if valeurSelectionTypeFichier == "1 fichier par canal + temps (NOM_FICHIER_tXX_chXX.tif)": numberOfZDepth = len(arrayOfImages[channelNumber]) if numberOfZDepth > maxNumberOfZDepth: maxNumberOfZDepth = numberOfZDepth for zNumber in range(len(arrayOfImages[channelNumber])): numberOfTime = len(arrayOfImages[channelNumber][zNumber]) if numberOfTime > maxNumberOfTimeStamps: maxNumberOfTimeStamps = numberOfTime if valeurSelectionTypeFichier == "1 fichier par canal et par profondeur (NOM_FICHIER_zXX_chXX.tif)": numberOfZDepth = len(arrayOfImages[channelNumber]) if numberOfZDepth > maxNumberOfZDepth: maxNumberOfZDepth = numberOfZDepth if valeurSelectionTypeFichier == "1 fichier par canal et par profondeur + temps (NOM_FICHIER_tXX_zXX_chXX.tif)": numberOfZDepth = len(arrayOfImages[channelNumber]) print(arrayOfImages[channelNumber]) if numberOfZDepth > maxNumberOfZDepth: maxNumberOfZDepth = numberOfZDepth for zNumber in range(len(arrayOfImages[channelNumber])): print(arrayOfImages[channelNumber][zNumber]) numberOfTime = len(arrayOfImages[channelNumber][zNumber]) if numberOfTime > maxNumberOfTimeStamps: maxNumberOfTimeStamps = numberOfTime hyperStack = ImageStack() #imageTitle = "HyperStack" print("C: "+str(maxNumberOfChannels)+", Z: "+str(maxNumberOfZDepth)+", T: "+str(maxNumberOfTimeStamps)) for timeNumber in range(maxNumberOfTimeStamps): for zDepthNumber in range(maxNumberOfZDepth): for channelNumber in range(maxNumberOfChannels): #print("Position: "+str(channelNumber)+", "+str(zDepthNumber)+", "+str(timeNumber)) currentImagePlus = arrayOfImages[channelNumber][zDepthNumber][timeNumber] #print("ImagePlus: "+str(currentImagePlus)) currentImagePlus.setC(channelNumber) currentImagePlus.setZ(zDepthNumber) currentImagePlus.setT(timeNumber) currentImageProcessor = currentImagePlus.getProcessor() hyperStack.addSlice(currentImageProcessor) hyperStackImagePlus = ImagePlus(imageTitle, hyperStack) #hyperStackImagePlus.show() if maxNumberOfChannels*maxNumberOfZDepth*maxNumberOfTimeStamps > 1: converter = HyperStackConverter() hyperStackImagePlus = converter.toHyperStack(hyperStackImagePlus, maxNumberOfChannels, maxNumberOfZDepth, maxNumberOfTimeStamps, valeurSelectionDisplayMode) if valeurSelectionTypeFichier == "1 fichier par canal + temps (NOM_FICHIER_tXX_chXX.tif)": hyperStackImagePlus = converter.toHyperStack(hyperStackImagePlus, maxNumberOfChannels, maxNumberOfTimeStamps, maxNumberOfZDepth, "xyctz", valeurSelectionDisplayMode); return hyperStackImagePlus
def extract_frame(imp, frame, channel): """ From a VirtualStack that is a hyperstack, contained in imp, extract the timepoint frame as an ImageStack, and return it. It will do so only for the given channel. """ stack = imp.getStack() # multi-time point virtual stack vs = ImageStack(imp.width, imp.height, None) for s in range(1, imp.getNSlices()+1): i = imp.getStackIndex(channel, s, frame) vs.addSlice(str(s), stack.getProcessor(i)) return vs
def SplitImage(ip, width, height): stack = ImageStack(width, height) for x in range(0,ip.width,width): for y in range(0,ip.height,height): roi = Roi(x,y,width,height) ip.setRoi(roi) ip2 = ip.crop() stack.addSlice(None, ip2) return stack
def get_substack(theImage,startSlice,endSlice): retStack = ImageStack(theImage.getWidth(),theImage.getHeight()) for i in range(startSlice,endSlice+1): theImage.setSliceWithoutUpdate(i) ip = theImage.getProcessor() newip = ip.duplicate() retStack.addSlice(newip) return(ImagePlus("dataimage",retStack))
def find_maxima_stack(imp, tolerance): stack = imp.getImageStack() stack_out = ImageStack(imp.width, imp.height) for i in range(1, imp.getNSlices() + 1): ip = stack.getProcessor(i) # findMaxima(ImageProcessor ip, double tolerance, double threshold, int outputType, boolean excludeOnEdges, boolean isEDM) ip_max = MaximumFinder().findMaxima(ip, tolerance, ImageProcessor.NO_THRESHOLD, MaximumFinder.IN_TOLERANCE, False, False) stack_out.addSlice(str(i), ip_max) #segip.invert() return ImagePlus("Maxima", stack_out)
def SplitImage(ip, width, height): stack = ImageStack(width, height) for x in range(0, ip.width, width): for y in range(0, ip.height, height): roi = Roi(x, y, width, height) ip.setRoi(roi) ip2 = ip.crop() stack.addSlice(None, ip2) return stack
def run(title): gd = GenericDialog("Record Desktop") gd.addNumericField("Max. frames:", 50, 0) gd.addNumericField("Milisecond interval:", 300, 0) gd.addSlider("Start in (seconds):", 0, 20, 5) gd.showDialog() if gd.wasCanceled(): return n_frames = int(gd.getNextNumber()) interval = gd.getNextNumber() / 1000.0 # in seconds delay = int(gd.getNextNumber()) snaps = [] try: while delay > 0: IJ.showStatus("Starting in " + str(delay) + "s.") time.sleep(1) # one second delay -= 1 IJ.showStatus("") System.out.println("Starting...") # start capturing robot = Robot() box = Rectangle(IJ.getScreenSize()) start = System.currentTimeMillis() / 1000.0 # in seconds last = start intervals = [] real_interval = 0 # Initial shot snaps.append(robot.createScreenCapture(box)) while 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 snaps.append(robot.createScreenCapture(box)) intervals.append(real_interval) else: time.sleep(interval / 5) # time in seconds # Create stack System.out.println("End") awt = snaps[0] stack = ImageStack(awt.getWidth(None), awt.getHeight(None), None) t = 0 for snap, real_interval in zip(snaps, intervals): stack.addSlice(str(IJ.d2s(t, 3)), ImagePlus("", snap).getProcessor()) snap.flush() t += real_interval ImagePlus("Desktop recording", stack).show() except Exception, e: print "Some error ocurred:" print e for snap in snaps: snap.flush()
def rot_around_x(input_stack): """do rotation around x axis""" output_slices = input_stack.getHeight(); output_width = input_stack.getWidth(); output_height = input_stack.getSize(); output_stack = ImageStack(output_width, output_height); for yidx in range(input_stack.getHeight()): IJ.showProgress(float(yidx)/output_slices); output_stack.addSlice(FloatProcessor(output_width, output_height, input_stack.getVoxels(0, yidx, 0, output_width, 1, output_height, []))); IJ.showProgress(1.0); return output_stack;
def make_tiled_imp(imp): """generate a ImageProcessor that is the input tiled 3 time horizontally""" ip = imp.getProcessor() stack = ImageStack(imp.getWidth(), imp.getHeight()) for idx in range(3): stack.addSlice(ip) temp_imp = ImagePlus("temp", stack) tile_imp = MontageMaker().makeMontage2(temp_imp, 3, 1, 1, 1, 3, 1, 0, False) temp_imp.close() return tile_imp
def multiply(imp, value): # check: http://rsb.info.nih.gov/ij/plugins/stack-contrast/index.htm stack = imp.getImageStack() stack_out = ImageStack(imp.width, imp.height) nz = stack.getSize() for iz in range(1, nz + 1): ip_out = stack.getProcessor(iz).duplicate() #print iz, correction ip_out.multiply(value) stack_out.addSlice(str(iz), ip_out) #segip.invert() return ImagePlus("Multiplied", stack_out)
def stackFromPaths(paths): firstIm = IJ.openImage(paths[0]) width = firstIm.getWidth() height = firstIm.getHeight() firstIm.close() ims = ImageStack(width, height) # assemble the ImageStack of the channel for path in paths: ims.addSlice(IJ.openImage(path).getProcessor()) imp = ImagePlus('Title', ims) imp.setDimensions(1, 1, len(paths)) # these have to be timeframes for trackmate return imp
def generateRotations(imp, backgroundValue): # Generate stack of rotations with noise ip = imp.getProcessor() rotations = ImageStack(ip.getWidth(), ip.getHeight()) for i in xrange(10): # up to 90 degrees ipr = ip.duplicate() ipr.setInterpolationMethod(ImageProcessor.BILINEAR) ipr.setBackgroundValue(backgroundValue) ipr.rotate(i * 10) ipr.noise(25) # sd = 25 rotations.addSlice(ipr) return rotations
def extractChannel(imp, nChannel, nFrame): """extract a channel from the image, at a given frame returning a new imagePlus labelled with the channel name""" stack = imp.getImageStack() ch = ImageStack(imp.width, imp.height) for i in range(imp.getNSlices()): index = imp.getStackIndex(nChannel, i, nFrame) ch.addSlice(str(i), stack.getProcessor(index)) imp3 = ImagePlus("Channel " + str(nChannel), ch).duplicate() stats = StackStatistics(imp3) IJ.setMinAndMax(imp3, stats.min, stats.max) return imp3
def extract_channel_frame(imp, nChannel, nFrame, title=""): """ Extract a stack for a specific color channel and timeframe """ # todo: preserve spatial calibration stack = imp.getImageStack() ch = ImageStack(imp.width, imp.height) for i in range(1, imp.getNSlices() + 1): index = imp.getStackIndex(nChannel, i, nFrame) ch.addSlice(str(i), stack.getProcessor(index)) if title: imp_out = ImagePlus(title, ch) else: imp_out = ImagePlus("Channel " + str(nChannel), ch) return imp_out
def createChannel(darray, h, w, z, nChannel): """ Create a stack for a specific color channel """ ch = ImageStack(w, h) # imp = ImagePlus("my new image", FloatProcessor(w, h)) # fp = imp.getProcessor() # fparray = zeros(w,h,'f') for i in range(0, z): # fparray[:][:]=doutarray[:][:][nChannel][i] # fp.setFloatArray(fparray) ch.addSlice( str(i), FloatProcessor(w, h, [doutarray[:][:][nChannel][i].tolist()])) return ImagePlus("Channel " + str(nChannel), ch)
def __end(self, event): if len(self.__iplist)==0 : IJ.showMessage("", "Stack is empty") return self.__iplist.sort(key = lambda ip : ip.width) self.__ipw=[ ip.getWidth() for ip in self.__iplist ] self.__iph=[ ip.getHeight() for ip in self.__iplist ] maxw=max(self.__ipw) maxh=max(self.__iph) if self.__enlarge : resizelist = [ ip.resize(maxw, maxh, True) for ip in self.__iplist ] else : resizelist = [] for ip in self.__iplist : tempip = ShortProcessor(maxw, maxh) xloc = int(math.floor((maxw/2.00) - (ip.width/2.00))) yloc = int(math.floor((maxh/2.00) - (ip.height/2.00))) tempip.copyBits(ip, xloc, yloc, Blitter.COPY) resizelist.append(tempip) ims = ImageStack(maxw, maxh) #for ip in resizelist : ims.addSlice("", ip) for i in range(len(resizelist)) : ims.addSlice(self.__labels[i], resizelist[i]) self.__impRes = ImagePlus(self.__name, ims) self.__impRes.show() self.__sens = [1 for i in range(len(self.__iplist)) ] if self.__appmedian : IJ.run(self.__impRes, "Median...", "radius=1 stack") if self.__align : self.__falign() if self.__avg : self.__favg() if self.__mosa : self.__fmosa() if self.__maxfinder : self.__fmaxfinder() if self.__fire : IJ.run(self.__impRes, "Fire", "") if self.__measures : self.__fmeasures() self.__sens[:] = [] self.__listrois[:] = [] self.__iplist[:] = [] self.__cellsrois[:] = [] self.__ipw[:] = [] self.__iph[:] = [] self.__init = False
def extractFrame(imp, nFrame): """extract a frame from the image, returning a new 16 bit imagePlus labelled with the channel name""" stack = imp.getImageStack() fr = ImageStack(imp.width, imp.height) for i in range(1, imp.getNSlices() + 1): for nChannel in range(1, imp.getNChannels() + 1): index = imp.getStackIndex(nChannel, i, nFrame) fr.addSlice(str(i), stack.getProcessor(index)) imp3 = ImagePlus("Frame " + str(nFrame), fr).duplicate() imp3.setDimensions(imp.getNChannels(), imp.getNSlices(), 1) comp = CompositeImage(imp3, CompositeImage.COMPOSITE) comp.show() return comp
def openUnstitched(group): print(group) ipArr = [] frameNo = 1 frameNoLink = {} nucIpArr = [] cmIpArr = [] for g in group: checkKeys = {k:g[k] for k in g if k not in ["channel", "fileName"]} existsNuc = False existsCm = False for gg in group: checkKeys2 = {k:g[k] for k in g if k not in ["channel", "fileName"]} if checkKeys2: if gg['channel'] == nucChannel: existsNuc = True elif gg['channel'] == cmChannel: existsCm = True if not (existsCm and existsNuc): continue fileName = g['fileName'] channel = g['channel'] checkKeys if channel == nucChannel: nucIpArr.append(opener.openImage(folderPath + fileName)) elif channel == cmChannel: cmIpArr.append(opener.openImage(folderPath + fileName)) nucStack = ImageStack(nucIpArr[0].width, cmIpArr[0].height) cmStack = ImageStack(nucIpArr[0].width, cmIpArr[0].height) for nucIp, cmIp in nucIpArr, cmIpArr: nucStack.addSlice(nucIp.getTitle(), nucIp.getProcessor()) cmStack.addSlice(cmIp.getTitle(), cmIp.getProcessor()) nucIp = ImagePlus("images{}".format(fileName), nucIpArr[0].getProcessor()) cmIp = ImagePlus("images{}".format(fileName), cmIpArr[0].getProcessor()) nucIp.setStack(nucStack) cmIp.setStack(cmStack) return nucIp, cmIp
def run_script(imp, close, far, cutoff): stack = imp.getImageStack() fin_stack = ImageStack(imp.width, imp.height) # iterate each slice in the stack for i in range(1, stack.getSize() + 1): # get progress IJ.showProgress(i, stack.getSize() + 1) # image processor converted to float to avoid byte problems ip = stack.getProcessor(i).convertToFloat() # pixels points to the array of floats pixels = ip.getPixels() # initial subtraction stddev = initial_subtract(pixels, imp.width, imp.height) mask = [255] * (imp.width * imp.height) # mask borders of image dependent on settings if far: fringe_mask(mask, imp.width, 2) elif close: fringe_mask(mask, imp.width, 1) else: pass # update mask if close: init_mask(pixels, mask) close_subtract(pixels, mask, imp.width, cutoff, stddev) if far: init_mask(pixels, mask) far_subtract(pixels, mask, imp.width, cutoff, stddev) if close or far: apply_mask(pixels, mask) fin_stack.addSlice(None, FloatProcessor(imp.width, imp.height, pixels, None)) # create new image from final stack imp_fin = ImagePlus(imp.title[:-4] + "_background-subtracted.tif", fin_stack) # keep the same image calibration imp_fin.setCalibration(imp.getCalibration().copy()) imp_fin.show() IJ.showProgress(1) # show progess bar
def attenuation_correction(imp, intensity_zmin, intensity_zmax): # check: http://rsb.info.nih.gov/ij/plugins/stack-contrast/index.htm stack = imp.getImageStack() stack_out = ImageStack(imp.width, imp.height) a = intensity_zmin b = intensity_zmax nz = imp.getNSlices() for iz in range(1, nz + 1): ip_out = stack.getProcessor(iz).duplicate() correction = (a+b)/2 * (1/(a-(a-b)*(iz-1)/(nz-1))) #print iz, correction ip_out.multiply(correction) stack_out.addSlice(str(iz), ip_out) #segip.invert() return ImagePlus("Attenuation_corrected", stack_out)
def retrieve_dapi(image, channel): # get stack from current image stack = image.getStack() #print(image.getStackSize(), stack.getSize()) final_stack = ImageStack(image.width, image.height) for i in range(1, image.getStackSize() + 1): countchannel = i % totchannels #print(i, countchannel, countchannel in channels) if (countchannel == channel): myslice = stack.getProcessor(i) final_stack.addSlice(str(i), myslice) return final_stack
def nearestZProject(imp1): relicedImp = Slicer().reslice(imp1) relicedStack = relicedImp.getStack() width = imp1.getWidth() height = imp1.getHeight() depth = imp1.getNSlices() topPixels = zeros('f', width * height) stack2 = ImageStack(width, height) for i in range(1, relicedImp.getNSlices()): pixels = relicedStack.getPixels(i) for x in xrange(width): for pixel in xrange(x, x + width * (depth - 1), width): #after finding the first pixel above the threshold value, add the value to the list if pixels[pixel] != 0: topPixels[i * width + x] = pixels[pixel] #break from looping the y when 1st threshold pixel is found is met -> increases speed drastically! Otherwise need an if statement every loop... break ip2 = FloatProcessor(width, height, topPixels, None) imp2 = ImagePlus("Nearest point proj", ip2) imp3 = imp2.resize(imp2.getWidth() * 2, imp2.getHeight() * 2, 'none') return imp3
def orthoStackFrom4D(imp): stkA = ArrayList() for i in range(1, imp.getNFrames()+1): e4d = Extractfrom4D() e4d.setGstarttimepoint(i) IJ.log("current time point" + str(i)) aframe = e4d.coreheadless(imp, 3) ortho = XYZMaxProject(aframe) orthoimp = ortho.getXYZProject() stkA.add(orthoimp) #orthoimp.show() stk = ImageStack(stkA.get(0).getWidth(), stkA.get(0).getHeight()) for item in stkA: stk.addSlice("slcie", item.getProcessor()) out = ImagePlus("out", stk) return out
def retrieve_dapi(image, channel): # get stack from current image stack = image.getStack() #print(image.getStackSize(), stack.getSize()) final_stack = ImageStack(image.width, image.height) for i in range(1, image.getStackSize()+1): countchannel = i % totchannels #print(i, countchannel, countchannel in channels) if (countchannel == channel): myslice = stack.getProcessor(i) final_stack.addSlice(str(i), myslice) return final_stack
def concatenateImagePlus(files, outfile): """concatenate images contained in files and save in outfile""" ''' if len(files) == 1: IJ.log(files[0] + " has only one time point! Nothing to concatenate!") return ''' options = ImporterOptions() options.setId(files[0]) options.setVirtual(1) options.setOpenAllSeries(1) options.setQuiet(1) images = BF.openImagePlus(options) imageG = images[0] nrPositions = len(images) options.setOpenAllSeries(0) for i in range(0, nrPositions): concatImgPlus = IJ.createHyperStack("ConcatFile", imageG.getWidth(), imageG.getHeight(), imageG.getNChannels(), imageG.getNSlices(), len(files), imageG.getBitDepth()) concatStack = ImageStack(imageG.getWidth(), imageG.getHeight()) IJ.showStatus("Concatenating files") for file in files: try: IJ.log(" Add file " + file) options.setSeriesOn(i,1) options.setId(file) image = BF.openImagePlus(options)[0] imageStack = image.getImageStack() sliceNr = imageStack.getSize() for j in range(1, sliceNr+1): concatStack.addSlice(imageStack.getProcessor(j)) image.close() options.setSeriesOn(i,0) except: traceback.print_exc() IJ.log(file + " failed to concatenate!") IJ.showProgress(files.index(file), len(files)) concatImgPlus.setStack(concatStack) concatImgPlus.setCalibration(image.getCalibration()) if len(images) > 1: outfileP = addPositionName(i+1,outfile) IJ.saveAs(concatImgPlus, "Tiff", outfileP) else: IJ.saveAs(concatImgPlus, "Tiff", outfile) concatImgPlus.close()
def getDICfocus(imp): stack = imp.getStack() focusStack = ImageStack(W,H) for t in range(1,T+1): sd = [0 for z in range(Z+1)] for z in range(1,Z+1): #get best focussed C2 (DIC) slices ip = stack.getProcessor(imp.getStackIndex(2,z,t)).convertToFloat() ip.findEdges() sd[z] = ImageStatistics.getStatistics(ip, Measurements.STD_DEV, cal).stdDev focusZ = sd.index(max(sd)) focusSlice = stack.getProcessor(imp.getStackIndex(2,focusZ,t)).convertToFloatProcessor() focusStack.addSlice("Z"+str(focusZ), focusSlice) #ImagePlus("DIC focus", focusStack).show() #exit(0) return focusStack
def calculateThreshold(image, roi, method): if roi != None: bounds = roi.getBounds() stack = image.getStack() newstack = ImageStack(bounds.width, bounds.height) for i in xrange(1, stack.getSize() + 1): ip = stack.getProcessor(i).duplicate() ip.fillOutside(roi) ip.setRoi(roi) c = ip.crop() newstack.addSlice(str(i), c) imp = ImagePlus("ThresholdImage", newstack) else: imp = image thresholder = Auto_Threshold() result = thresholder.exec(imp, method, False, False, True, False, False, True) return result
def make_montage(self, xy="", montage_name=""): if self.channels_to_montage == None: channels_to_montage = self.channel_names else: channels_to_montage = self.channels_to_montage w = self.cropped_imps[self.channel_names[0]].width h = self.cropped_imps[self.channel_names[0]].height new_stack = ImageStack(w, h) # print self.cropped_imps.keys() for channel in channels_to_montage: img = self.cropped_imps[channel].getProcessor() new_stack.addSlice(img) tomontage = ImagePlus("to montage", new_stack) montager = MontageMaker() self.montage = montager.makeMontage2( tomontage, len(channels_to_montage), 1, 1, 1, len(channels_to_montage), 1, 0, 0 ) directory = self.outdir file_name = self.name save_as = os.path.join(directory, "%s_%s_montage.tif" % (file_name, xy)) IJ.save(self.montage, save_as)
def Extract_Red_Channel(color): imp = IJ.getImage() stack = imp.getImageStack() print "number of slices:", imp.getNSlices() # A list of red slices reds = [] # Iterate each slice in the stack for i in xrange(1, imp.getNSlices()+1): # Get the ColorProcessor slice at index i cp = stack.getProcessor(i) # Get its green channel as a FloatProcessor fp = cp.toFloat(0, None) # ... and store it in a list reds.append(fp) # Create a new stack with only the green channel stack2 = ImageStack(imp.width, imp.height) for fp in reds: stack2.addSlice(None, fp) # Create a new image with the stack of green channel slices imp2 = ImagePlus("Red channel", stack2) # Set a green look-up table: IJ.run(imp2, "Red", "") imp2.show()
def rotateStack(imp, axis, radian): modelM = AffineModel3D() modelM.rotate(axis, radian) print 'model: ', modelM.toString() ww = imp.getWidth() hh = imp.getHeight() dd = imp.getImageStackSize() mapping = InverseTransformMapping( modelM ); minA = jarray.Array.newInstance(Float.TYPE, 3) maxA = jarray.Array.newInstance(Float.TYPE, 3) minA[0] = 0.0 minA[1] = 0.0 minA[2] = 0.0 maxA[0] = ww-1 maxA[1] = hh-1 maxA[2] = dd-1 minA, maxA, destsizeA = ReCalcStackSize(modelM, minA, maxA) print destsizeA[0], destsizeA[1], destsizeA[2] nww = int(destsizeA[0]) nhh = int(destsizeA[1]) ndd = int(destsizeA[2]) ReCalcOffset(modelM, minA) print 'recalculated model: ', modelM.toString() ip = imp.getStack().getProcessor( 1 ).createProcessor( 1, 1 ) target = ImageStack(nww, nhh) for s in range(ndd): ip = ip.createProcessor(nww, nhh) mapping.setSlice( s + 1) mapping.mapInterpolated( imp.getStack(), ip ) target.addSlice( "", ip ) impout = ImagePlus("out", target) return impout
# extracting stack time frames and convert to ortho imp = IJ.getImage() stkA = ArrayList() for i in range(1, 4): #for i in range(1, imp.getNFrames()): e4d = Extractfrom4D() e4d.setGstarttimepoint(i) IJ.log("current time point" + str(i)) aframe = e4d.coreheadless(imp, 3) ortho = XYZMaxProject(aframe) orthoimp = ortho.getXYZProject() stkA.add(orthoimp) #orthoimp.show() stk = ImageStack(stkA.get(0).getWidth(), stkA.get(0).getHeight()) for item in stkA: stk.addSlice("slcie", item.getProcessor()) out = ImagePlus("out", stk) #out.setCalibration(imp.getCalibration().copy()) IJ.run(out, "Grays", ""); IJ.run(out, "RGB Color", ""); # load data from file filepath = '/Users/miura/Dropbox/Mette/20_23h/20_23hrfull_corrected_1_6_6_netdispZ40.csv' filename = os.path.basename(filepath) newfilename = os.path.join(os.path.splitext(filename)[0], '_plotStack.tif') out.setTitle(os.path.basename(filename)+'_OutStack.tif') PLOT_ONLY_IN_FRAME1 = False
def scaleandfilter(infile,outfile,scalex,scaley,scalez,anisofilter,runtube): print ("infile is: "+infile) imp = Opener().openImage(infile) print imp print "scalex = %f; scaley = %f ; scalez = %f" % (scalex,scaley,scalez) # Rescale cal = imp.getCalibration() iml = ImgLib.wrap(imp) scaledimg = Scale3D(iml, scalex, scaley, scalez) imp2=ImgLib.wrap(scaledimg) # find range of pixel values for scaled image from mpicbg.imglib.algorithm.math import ComputeMinMax # (for imglib2 will be: net.imglib2.algorithm.stats) minmax=ComputeMinMax(scaledimg) minmax.process() (min,max)=(minmax.getMin().get(),minmax.getMax().get()) # Make a copy of the stack (converting to 8 bit as we go) stack = ImageStack(imp2.width, imp2.height) print "min = %e, max =%e" % (min,max) for i in xrange(1, imp2.getNSlices()+1): imp2.setSliceWithoutUpdate(i) ip=imp2.getProcessor() # set range ip.setMinAndMax(min,max) stack.addSlice(str(i), ip.convertToByte(True)) # save copy of calibration info cal=imp.getCalibration() # close original image imp.close() # make an image plus with the copy scaled = ImagePlus(imp2.title, stack) # Deal with calibration info which didn't seem to come along for the ride cal.pixelWidth/=scalex cal.pixelHeight/=scaley cal.pixelDepth/=scalez scaled.setCalibration(cal) print "dx = %f; dy=%f; dz=%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth) intif=infile+".tif" outtif=infile+"-filtered.tif" if anisofilter.upper() != 'FALSE': print("saving input file as "+intif) f=FileSaver(scaled) f.saveAsTiffStack(intif) scaled.close() # anisotropic filtering anisopts="-scanrange:10 -tau:2 -nsteps:2 -lambda:0.1 -ipflag:0 -anicoeff1:1 -anicoeff2:0 -anicoeff3:0" anisopts=anisopts+" -dx:%f -dy:%f -dz:%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth) if sys.version_info > (2, 4): #for testing # subprocess.check_call(["cp",intif,outtif]) subprocess.check_call([anisofilter]+anisopts.split(' ')+[intif,outtif]) else: os.system(" ".join([anisofilter]+anisopts.split(' ')+[intif,outtif])) # Open anisofilter output back into Fiji print("Opening output tif: "+outtif) scaled = Opener().openImage(outtif) scaled.setCalibration(cal) # Hessian (tubeness) print("Running tubeness") if(runtube): tp=TubenessProcessor(1.0,False) result = tp.generateImage(scaled) IJ.run(result, "8-bit","") else: result=scaled # Save out file fileName, fileExtension = os.path.splitext(outfile) print("Saving as "+fileExtension+": "+outfile) if fileExtension.lower()=='.nrrd': nw=Nrrd_Writer() nw.setNrrdEncoding("gzip") nw.save(result,outfile) else: # Save to PIC IJ.run(result,"Biorad ...", "biorad=["+outfile+"]") scaled.close() result.close()
def run(): """ Loads an image stack which contains both reference and target images for the registration Scales the images to have their largest side equal to longSide Registration is performed: - translation (brute force optimization) - rotation (brute force optimization) - sift registration - bunwarpj registration Calculation of the errors by different methods """ # load the input stack as an ImagePlus imp = IJ.openImage(filePath.getAbsolutePath()) stack = imp.getStack() sizeZ = imp.getStackSize() LAND_MARKS = 0 # Copy the reference and target slice refId = 1 ref = stack.getProcessor(refId).duplicate() if (Scale == 1): [ref, s] = scaleLongSide(ref, longSide) sizeZ = min(sizeZ, maxSlice) stackReg = ImageStack(ref.getWidth(), ref.getHeight()) stackReg.addSlice(ref) # = stack.duplicate() for i in range(2, sizeZ+1): targetId = i target = stack.getProcessor(targetId).duplicate() # Scale the slices: scale the reference slice using the longSide parameter, and use the same scale for the target slice. if (Scale == 1): target = scale(target, s) #ImagePlus('Ref',ref).show() #ImagePlus('Target',target).show() if (Reg == 1): if (translationReg == 1): target = translation(ref, target) if (rotationReg == 1): [rot, target] = rotationSingle(ref,target,rotationStep) if (siftReg == 1): [roiRef, roiTarget] = siftSingle(ref, target) impTarget = ImagePlus('Target',target) impTarget.setRoi(roiTarget) #impTarget.show() impRef = ImagePlus('Ref',ref) impRef.setRoi(roiRef) #impRef.show() LAND_MARKS = 1 if (bunwarpjReg == 1): target = bunwarpjSingle(impRef, impTarget, LAND_MARKS, 'direct_transfo_' + str(i) + '.txt', 'inverse_transfo_' + str(i) + '.txt') impTarget = ImagePlus('unwarpj_target', target) #impTarget.show() fileName = 'target_id' + str(targetId) + '.tif' IJ.saveAs(impTarget, "Tiff", os.path.join(saveDir.getAbsolutePath(), fileName)) #stackReg.setProcessor(target.convertToShortProcessor(), i) stackReg.addSlice(target) if (calculateError == 1): eCorrelation = zeros(sizeZ, 'f') eMSE = zeros(sizeZ, 'f') eMSE_ROI = zeros(sizeZ, 'f') eRMSE = zeros(sizeZ, 'f') eNRMSE = zeros(sizeZ, 'f') eCVRMSE = zeros(sizeZ, 'f') for i in range(1, sizeZ+1): ip = stackReg.getProcessor(i).duplicate() #ImagePlus('test',ip).show() eCorrelation[i-1], eMSE[i-1], eMSE_ROI[i-1], eRMSE[i-1], eNRMSE[i-1], eCVRMSE[i-1] = measureError(ref,ip) errorFileName = 'error.txt' errorFilePath = os.path.join(saveDir.getAbsolutePath(), errorFileName) writeCSV( errorFilePath, [eCorrelation,eMSE, eMSE_ROI, eRMSE,eNRMSE,eCVRMSE], ["Correlation","MSE","MSE_ROI","RMSE","N_RMSE","CV_RMSE"] )
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)
from java.io import File from ij import IJ,WindowManager,ImagePlus,ImageStack from ij.process import FloatProcessor path = "/home/ab/Dropbox/arabido/test/" imp = WindowManager.getCurrentImage() stack = imp.getStack() N_larg = 4 N_lon = 4 # 2 - Create a new stack to store the result new_stack = ImageStack(imp.width, imp.height) for i in range(1, imp.getNSlices()+1): slice = stack.getProcessor(i) red = slice.toFloat(0, None) green = slice.toFloat(1, None) blue = slice.toFloat(2, None) pix_red = red.getPixels() pix_green = green.getPixels() pix_blue = blue.getPixels() new_red = FloatProcessor(imp.width, imp.height) pix_new_red = new_red.getPixels() new_green = FloatProcessor(imp.width, imp.height) pix_new_green = new_green.getPixels()