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(): 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 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 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 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 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 main(): imp = WindowManager.getCurrentImage() width, height, nChannels, nSlices, nFrames = imp.getDimensions() canny_stack = ImageStack() for i in range(nFrames): slice = Duplicator().run( imp, 1, # firstC 1, # lastC 1, # firstZ 1, # lastZ i, # firstT i) # lastT proc = i / nFrames IJ.log("Processing slice {}/{}...".format(i, nFrames)) canny_slice = _singleCanny(slice) ip = canny_slice.getProcessor() canny_stack.addSlice(ip) canny_stack = ImagePlus("canny_stack", canny_stack) canny_stack.show() IJ.log("Canny edge detection finished.") return
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 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 preprocess_slices_giv_im(image_num,file_inpath,file_outpath): imp = IJ.openImage(file_inpath) file_names,rows = getLabels() stack = imp.getImageStack() stack2 = ImageStack(imp.width,imp.height) for j in range(imp.getNSlices()): if rows[j][image_num]== '0': ip = stack.getProcessor(j+1) NormalizeLocalContrast.run(ip, 341, 326, 4, True, True) imagep = ImagePlus("imp",ip) IJ.run(imagep, "Non-local Means Denoising", "sigma=15 smoothing_factor=1 slice") imagep.setRoi(2,0,336,320); IJ.run(imagep, "Level Sets", "method=[Active Contours] use_level_sets grey_value_threshold=50 distance_threshold=0.50 advection=2.20 propagation=1 curvature=1 grayscale=30 convergence=0.0025 region=inside") fimp = IJ.getImage() #fip = fimp.getProcessor() fimp = removeSmallCCs(fimp) fip = fimp.getProcessor() stack2.addSlice(fip) print("process") else: ip = stack.getProcessor(j+1) stack2.addSlice(ip) final_imp = ImagePlus("image",stack2) output = "nrrd=["+file_outpath+"]" IJ.run(final_imp, "Nrrd ... ", output)
import time import gc from ij.plugin.frame import RoiManager from ij.gui import Roi def segVOI_image_series(folder_in,folder_out,filepath_labels,x_len,y_len): """ Segment VOIs of a 3D image where whole 3D image series and slices which contain VOIs are given """ file_names,rows = getLabels(filepath_labels) for i in range(len(file_names)): imp = IJ.openImage(os.path.join(folder_in, file_names[i])) print(os.path.join(folder_in, file_names[i])) stack = imp.getImageStack() stack2 = ImageStack(imp.width,imp.height) blankim = IJ.createImage("blank", "8-bit black", imp.width, imp.height, 1) ipb= blankim.getProcessor() for j in range(imp.getNSlices()): if rows[j][i]== '0': ip = stack.getProcessor(j+1) #NormalizeLocalContrast.run(ip, 341, 326, 4, True, True) imagep = ImagePlus("imp",ip) IJ.run(imagep, "Non-local Means Denoising", "sigma=10 smoothing_factor=1 slice") imagep.setRoi(1,1,x_len,y_len); IJ.run(imagep, "Level Sets", "method=[Active Contours] use_level_sets grey_value_threshold=50 distance_threshold=0.50 advection=2.20 propagation=1 curvature=1 grayscale=30 convergence=0.03 region=inside") fimp = IJ.getImage() #fip = fimp.getProcessor() fimp = removeSmallCCs(fimp)
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 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 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 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 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 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 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 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 extract_channel(imp_max, Channel_1, Channel_2): stack = imp_max.getImageStack() ch_1 = ImageStack(imp_max.width, imp_max.height) ch_1.addSlice(str(Channel_1), stack.getProcessor(Channel_1)) ch_2 = ImageStack(imp_max.width, imp_max.height) ch_2.addSlice(str(Channel_2), stack.getProcessor(Channel_2)) ch1 = ImagePlus("Neuron" + str(Channel_1), ch_1) ch2 = ImagePlus("Glioma" + str(Channel_2), ch_2) ch1_1 = ch1.duplicate() ch2_1 = ch2.duplicate() ip1 = ch1_1.getProcessor().convertToFloat() ip2 = ch2_1.getProcessor().convertToFloat() return ip1, ip2
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 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 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 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 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 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