def main(): # Open a .ome.tif image from the Flexoscope. impath = IJ.getFilePath("Choose .ome.tiff file") channels = Opener.openUsingBioFormats(impath) # Show image # imp.show() # straight to channels object sames memory. # Split channels. channels = ChannelSplitter().split(channels) # Process channel 1. # subtractzproject(imp, projectionMethod="Median") channels[1] = ImagePlus() channels.append(ImagePlus()) channels[1] = subtractzproject(channels[0]) IJ.run(channels[0], "Enhance Contrast...", "saturated=0.3 normalize process_all use") IJ.run(channels[0], "8-bit", "") IJ.run(channels[1], "Square", "stack") IJ.run(channels[1], "Enhance Contrast...", "saturated=0.3 normalize process_all use") IJ.run(channels[1], "8-bit", "") # Merge channels. merge = RGBStackMerge().mergeChannels(channels, True) # boolean keep merge.show()
def ThresholdMaxEntropy(imp0): """Thresholds image and returns thresholded image, merge code still quite clumsy but functional""" imp0 = IJ.getImage() impthres = imp0.duplicate() imp01 = ImagePlus("Channel1", ChannelSplitter.getChannel(imp0, 1)) imp02 = ImagePlus("Channel2", ChannelSplitter.getChannel(imp0, 2)) imp001 = imp01.duplicate() imp002 = imp02.duplicate() IJ.setAutoThreshold(imp001, "MaxEntropy dark") IJ.run(imp001, "Convert to Mask", "") IJ.run(imp001, "Divide...", "value=255") IJ.setAutoThreshold(imp002, "MaxEntropy dark") IJ.run(imp002, "Convert to Mask", "") IJ.run(imp002, "Divide...", "value=255") ic = ImageCalculator() imp0001 = ic.run("Multiply create", imp01, imp001) ic2 = ImageCalculator() imp0002 = ic2.run("Multiply create", imp02, imp002) imp0001.copy() impthres.setC(1) impthres.paste() imp0002.copy() impthres.setC(2) impthres.paste() imp01.close() imp02.close() imp001.close() imp002.close() imp0001.close() imp0002.close() return impthres
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 calculate_mean_r(imp, ring_rois, centres): """calculate the average distance of the cell surface from the vessel axis""" w = imp.getWidth() h = imp.getHeight() rp = FloatProcessor(w, h) rpix = rp.getPixels() for lidx, (roi, centre) in enumerate(zip(ring_rois, centres)): for thetaidx, (x, y) in enumerate( zip(roi.getPolygon().xpoints, roi.getPolygon().xpoints)): rpix[lidx * w + thetaidx] = math.sqrt((x - centre[0])**2 + (y - centre[1])**2) rimp = ImagePlus("Radii", rp) IJ.setAutoThreshold(rimp, "Intermodes light") bp = rimp.createThresholdMask() bp.dilate() bp.erode() mask_imp = ImagePlus("Mask", bp) IJ.run(mask_imp, "Create Selection", "") roi = mask_imp.getRoi() rimp.setRoi(roi) mean_r = rimp.getStatistics().mean rimp.close() mask_imp.close() return mean_r
def main(): # Import files. imp = IJ.openImage("http://imagej.nih.gov/ij/images/confocal-series.zip") # Retrieve float image. fp = imptofloat(imp) IJ.log("{}\n{}".format(fp, fp.medianFilter())) # Perform focus projection. stack = maxfilter(fp, kernalSize=11) # Generate some output. IJ.log("{}\n{}".format(fp, stack)) out = ImagePlus("filter", stack) out.show() channels = ChannelSplitter().split(imp) channel1 = channels[0].getImageStack() depth = depthmap(channel1) test = ImagePlus("test", depth) test.show() final = projectfocus(channel1, depth) final = ImagePlus("final", final) final.show()
def save_singleplanes(imp, savepath, metainfo, mode='TZC', format='tiff'): """ This function is still in testing. """ titleext = imp.getTitle() title = os.path.splitext(titleext)[0] if mode == 'TZC': for t in range(metainfo['SizeT']): for z in range(metainfo['SizeZ']): for c in range(metainfo['SizeC']): # set position - channel, slice, frame imp.setPosition(c + 1, z + 1, t + 1) numberedtitle = title + "_t" + IJ.pad(t, 2) + "_z" + IJ.pad(z, 4) + "_c" + IJ.pad(c, 4) + "." + format stackindex = imp.getStackIndex(c + 1, z + 1, t + 1) aframe = ImagePlus(numberedtitle, imp.getStack().getProcessor(stackindex)) outputpath = os.path.join(savepath, numberedtitle) IJ.saveAs(aframe, "TIFF", outputpath) if mode == 'Z': c = 0 t = 0 for z in range(metainfo['SizeZ']): # set position - channel, slice, frame imp.setPosition(c + 1, z + 1, t + 1) znumber = MiscTools.addzeros(z) numberedtitle = title + "_z" + znumber + "." + format stackindex = imp.getStackIndex(c + 1, z + 1, t + 1) aframe = ImagePlus(numberedtitle, imp.getStack().getProcessor(stackindex)) outputpath = os.path.join(savepath, numberedtitle) IJ.saveAs(aframe, "TIFF", outputpath)
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 GetSigmaWavelet(ip,RWavelet,boundRoi=None): '''Returns normalized sigma2,skew,kurtosis of a image after applying a wavelet of scale Rwavelet in a given roi''' #Create a copy of the image to filter fpInicial = ip.duplicate() impInitial = ImagePlus("ImagenInicial",fpInicial) #Filter image A=LOG3DCaso5(False) input = imageware.Builder.create(impInitial,3); #Float=3, Double=4 Output=A.doLoG(input,RWavelet,RWavelet) imp2=ImagePlus(" ", Output.buildImageStack()) #invert the convolved image pixelsConv=imp2.getProcessor() pixelsConv=pixelsConv.getPixels() for i in xrange(len(pixelsConv)): pixelsConv[i]=(-1)*pixelsConv[i] #Measure the statistics fpConv=FloatProcessor(ip.width, ip.height, pixelsConv, None) imp3=ImagePlus("ImagenConvolucionada",fpConv) imp3.setRoi(boundRoi) measurements = M.MEAN|M.STD_DEV|M.KURTOSIS|M.SKEWNESS stats = imp3.getStatistics(measurements) NSkew=round(stats.skewness*stats.stdDev**3,7) return NSkew
def ifft(imp, imp2, width, height): from edu.emory.mathcs.parallelfftj import DoubleTransformer from edu.emory.mathcs.parallelfftj import SpectrumType from ij import IJ, ImagePlus, ImageStack from ij.process import ImageProcessor, FloatProcessor import cmath, math b = [ complex(x, y) for x, y in zip([val for val in imp.getProcessor().getPixels()], [val for val in imp2.getProcessor().getPixels()]) ] f1 = [ cmath.exp(-1j * math.pi * (x + y)) for x in range(width) for y in range(height) ] #See forward fft for old centering loop. imp_r = ImagePlus( "real", FloatProcessor(width, height, [(x * y).real for x, y in zip(f1, b)])) imp_i = ImagePlus( "IMAGINARY", FloatProcessor(width, height, [(x * y).imag for x, y in zip(f1, b)])) FFT1 = DoubleTransformer(imp_r.getStack(), imp_i.getStack()) FFT1.ifft(1) #returns either unweighted or weighted r = FFT1.toImagePlus(SpectrumType.REAL_PART) i = FFT1.toImagePlus(SpectrumType.IMAG_PART) a = [ complex(x, y) for x, y in zip([val for val in r.getProcessor().getPixels()], [val for val in i.getProcessor().getPixels()]) ] c = [(x * y) for x, y in zip(f1, a)] return (c)
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 back_substraction(ip1, ip2, radius_background): bgs=BackgroundSubtracter() bgs.rollingBallBackground(ip1, radius_background, False, False, True, True, True) bgs.rollingBallBackground(ip2, radius_background, False, False, True, True, True) imp1 = ImagePlus("ch1 back sub", ip1) imp2 = ImagePlus("ch2 back sub", ip2) return imp1, imp2
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 test_maskIP(): imp = IJ.openImage(filePath.getAbsolutePath()) stack = imp.getStack() ip1 = stack.getProcessor(1).duplicate() ip2 = stack.getProcessor(2).duplicate() mask1 = maskIP(ip1) mask2 = maskIP(ip2) ImagePlus('mask1', mask1).show() ImagePlus('mask2', mask2).show()
def rot3d(imp, axis='x'): """pare back Slicer to implement whole-image, +90* rotations that return ImagePlus""" if imp.getType()==ImagePlus.COLOR_256 or imp.getType()==ImagePlus.COLOR_RGB: raise NotImplementedError("Handling of colour images isn't implemented yet"); IJ.showStatus("Rotating around {}-axis...".format(axis)) title = imp.getTitle(); original_cal = imp.getCalibration(); new_cal = original_cal; if imp.getNChannels > 1: split_ch = ChannelSplitter().split(imp); else: split_ch = [imp]; out_imps = []; if axis=='x': for ch_imp in split_ch: input_stack = ch_imp.getStack(); output_stack = rot_around_x(input_stack); out_imps.append(ImagePlus(title, output_stack)); new_cal.pixelHeight = original_cal.pixelDepth; new_cal.pixelDepth = original_cal.pixelHeight; elif axis=='y' or axis=='-y': for ch_imp in split_ch: if axis[0]=='-': input_stack = StackProcessor(ch_imp.getStack()).rotateLeft(); else: input_stack = StackProcessor(ch_imp.getStack()).rotateRight(); output_stack = rot_around_x(input_stack); if axis[0]=='-': final_stack = StackProcessor(output_stack).rotateLeft(); else: final_stack = StackProcessor(output_stack).rotateRight(); out_imps.append(ImagePlus(title, final_stack)); new_cal.pixelWidth = original_cal.pixelDepth; new_cal.pixelDepth = original_cal.pixelWidth; elif axis=='z' or axis=='-z': for ch_imp in split_ch: if axis[0]=='-': output_stack = StackProcessor(ch_imp.getStack()).rotateLeft(); else: output_stack = StackProcessor(ch_imp.getStack()).rotateRight(); out_imps.append(ImagePlus(title, output_stack)); new_cal.pixelWidth = original_cal.pixelHeight; new_cal.pixelHeight = original_cal.pixelWidth; else: raise NotImplementedError("Please check which axis you've chosen - if not (x, +/-y, +/-z) then it's not implemented..."); imp.changes = False; imp.close(); if len(out_imps) > 1: out_imp = RGBStackMerge().mergeChannels(out_imps, False); else: out_imp = out_imps[0]; out_imp.setCalibration(new_cal); return out_imp;
def hdist(ip1, ip2): mask1 = ImagePlus('mask1', ip1) mask2 = ImagePlus('mask2', ip2) # make outlines from the masks IJ.run(mask1, "Outline", "") IJ.run(mask2, "Outline", "") hd = Hausdorff_Distance() hd.exec(mask1, mask2) return hd.getHausdorffDistance(), hd.getAveragedHausdorffDistance()
def test_maskIlntersection(): """ Test of the function: maskIntersection(ip1, ip2) """ # load the input stack as an ImagePlus imp = IJ.openImage(filePath.getAbsolutePath()) stack = imp.getStack() sizeZ = imp.getStackSize() ip1 = stack.getProcessor(1).duplicate() ip2 = stack.getProcessor(2).duplicate() ImagePlus('ip1', ip1).show() ImagePlus('ip2', ip2).show() ImagePlus('intersection', maskIntersection(ip1, ip2)).show()
def back_substraction(ip1, ip2, radius_background): bgs=BackgroundSubtracter() bgs.rollingBallBackground(ip1, radius_background, False, False, True, True, True) bgs.rollingBallBackground(ip2, radius_background, False, False, True, True, True) imp1 = ImagePlus("ch1 back sub", ip1) imp2 = ImagePlus("ch2 back sub", ip2) IJ.run(imp1, "Enhance Contrast", "saturated=0.35") IJ.run(imp2, "Enhance Contrast", "saturated=0.35") return imp1, imp2
def save(self, e): # open the other channels d1_filename = path.join(self.input_path, self.name + '_D1.tif') d2_filename = path.join(self.input_path, self.name + '_D2.tif') self.d1_image = ImagePlus(d1_filename) #read the image print "d1 image opened" self.d2_image = ImagePlus(d2_filename) #read the image print "d2 image opened" for image in [self.dapi_image, self.d1_image, self.d2_image]: print "saving rois for image " + image.getTitle() save_rois(image, self.corners_cleaned, self.L, self.output_path) print "ROIs saved"
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 siftSingle(ref, target): """ perform SIFT registration for one image """ impRef = ImagePlus('Sift_source', ref) impTarget = ImagePlus('Sift_target', target) expected_transformation = 'Similarity' initial_gaussian_blur = 2 feature_descriptor_size = 8 imp = ImagePlus('siftRefTest', ref) t = SIFT_ExtractPointRoi() t.exec(impRef, impTarget) roiRef = impRef.getRoi() roiTarget = impTarget.getRoi() return roiRef, roiTarget
def applyFilter(stackName): imp = IJ.openImage(stackName) stack = imp.getImageStack() for i in xrange(1, imp.getNSlices() + 1): image = ImagePlus(str(i), stack.getProcessor(i)) IJ.run(image, "Auto Threshold", "method=Li white") #IJ.run(image, "Analyze Particles...", "size= 1000-Infinity circularity=0.00-1.00 show=Masks in_situ") imp2 = ImagePlus("Threshold", stack) fs = FileSaver(imp2) print "Saving filtered stack" fs.saveAsTiff(stackName[:-4] + "-filtered(Li).tif")
def mousePressed(self, event): from ij import IJ, ImagePlus from ij.process import FloatProcessor import math from ij.plugin import ImageCalculator imp = IJ.getImage() imp.setSlice(3) ip = imp.getProcessor().convertToFloat() # as a copy pixels = ip.getPixels() imp.setSlice(2) ip1 = imp.getProcessor().convertToFloat() # as a copy pixels1 = ip1.getPixels() imp.setSlice(1) ip2 = imp.getProcessor().convertToFloat() # as a copy pixels2 = ip2.getPixels() canvas = event.getSource() p = canvas.getCursorLoc() imp = canvas.getImage() x = p.x * 1.0000 y = p.y * 1.0000 nx = x - imp.width / 2 ny = y - imp.height / 2 n_y = ny * -1 n_xx = nx / imp.width / 2 n_yy = n_y / imp.height / 2 z = math.sqrt(n_xx * n_xx + n_yy * n_yy) z1 = math.sqrt(1 - z * z) Xdir = map(lambda x: x * n_xx, pixels2) Ydir = map(lambda x: x * n_yy, pixels1) Zdir = map(lambda x: x * z1, pixels) ip3 = FloatProcessor(ip.width, ip.height, Xdir, None) imp3 = ImagePlus("", ip3) ip4 = FloatProcessor(ip.width, ip.height, Ydir, None) imp4 = ImagePlus("", ip4) ip5 = FloatProcessor(ip.width, ip.height, Zdir, None) imp5 = ImagePlus("", ip4) imp6 = ImageCalculator().run("Add create 32-bit stack", imp3, imp4) imp7 = ImageCalculator().run("Add create 32-bit stack", imp5, imp6) imp7.setTitle("Lighting Direction") imp7.show()
def apply_filter3d(imp, radiusx=5, radiusy=5, radiusz=5, filtertype='MEDIAN'): # initialize filter f3d = Filters3D() # create filter dictionary for 3d filters filterdict = {} filterdict['MEAN'] = f3d.MEAN filterdict['MIN'] = f3d.MIN filterdict['MAX'] = f3d.MAX # filterdict['MAXLOCAL'] = f3d.MAXLOCAL # did not work filterdict['MEDIAN'] = f3d.MEDIAN filterdict['VAR'] = f3d.VAR stack = imp.getStack() # get the stack within the ImagePlus newstack = f3d.filter(stack, filterdict[filtertype], radiusx, radiusy, radiusz) imp = ImagePlus('Filtered 3D', newstack) return imp
def showAsComposite(images, title="Composite", show=True): imps = [] # Collect all images as ImagePlus, checking that they have the same XY dimensions. # (Z doesn't matter) dimensions = None for img in images: if isinstance(img, ImagePlus): imps.append(img) else: imps.append(IL.wrap(img, "")) if not dimensions: dimensions = [imps[-1].getWidth(), imps[-1].getHeight()] else: if imps[-1].width != dimensions[0] or imps[-1].getHeight( ) != dimensions[1]: print "asComposite: dimensions mistach." return imp = ImagePlus(title, StacksAsChannels([imp.getStack() for imp in imps])) imp.setDimensions(len(imps), max(imp.getStack().getSize() for imp in imps), 1) comp = CompositeImage(imp, CompositeImage.COMPOSITE) if show: comp.show() print imp.getNChannels(), imp.getNSlices(), imp.getNFrames( ), "but imps: ", len(imps) return comp
def navigate2DROI(img, interval, indexZ=0, title="ROI"): """ Use a FloatProcessor to visualize a 2D slice of a 3D image of any pixel type. Internally, uses a ViewFloatProcessor with an editable Interval. Here, a SourceNavigation (a KeyListener) enables editing the Interval and therefore the FloatProcessor merely shows that interval of the source img. img: the source 3D RandomAccessibleInterval. interval: the initial interval of img to view. Must be smaller than 2 GB. indexZ: the initial Z index to show. title: the name to give the ImagePlus. """ img = convert(img, FloatType) vsp = ViewFloatProcessor(img, interval, indexZ) imp = ImagePlus(title, vsp) imp.show() canvas = imp.getWindow().getCanvas() # Place the SourceNavigation KeyListener at the top of the list of KeyListener instances kls = canvas.getKeyListeners() for kl in kls: canvas.removeKeyListener(kl) canvas.addKeyListener(SourceNavigation(vsp, imp)) for kl in kls: canvas.addKeyListener(kl) return imp
def open_image(): """ opens an image, returns an imagePlus object and its name in that order """ # Prompt user for the input image file. print "open_image begin" op = OpenDialog("Choose input image...", "") if op.getPath() == None: sys.exit('User canceled dialog') # open selected image and prepare it for analysis inputName = op.getFileName() inputDirPath = op.getDirectory() inputPath = inputDirPath + inputName # Strip the suffix off of the input image name if inputName[-4] == ".": inputPrefix = inputName[:-4] # assumes that a suffix exists else: inputPrefix = inputName #opens image and returns it. inputImp = ImagePlus(inputPath) print "open_image finis" return inputImp, inputPrefix, inputDirPath
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()