def createMask(self, source): mask = FloatProcessor(source.getWidth(), source.getHeight()) maskColor = 0x0000ff00 sourcePixels = source.getPixels() n = len(sourcePixels) maskPixels = mask.getPixels() for i in xrange(n): sourcePixel = sourcePixels[i] & 0x00ffffff if sourcePixel == maskColor: maskPixels[i] = 0 else: maskPixels[i] = 1 mask.setPixels(maskPixels) return mask
def doMap(patch, roi, background=0.0, interpolate=False, floatp=False): if floatp: target = FloatProcessor(roi.width, roi.height) else: target = ShortProcessor(roi.width, roi.height) if background != 0.0: target.setValue(background) target.setRoi(0, 0, roi.width, roi.height) target.fill() t = TranslationModel2D() t.set(float(-roi.x), float(-roi.y)) ctl = CoordinateTransformList() ctl.add( patch.getFullCoordinateTransform() ) ctl.add( t ) mesh = CoordinateTransformMesh( ctl, patch.getMeshResolution(), patch.getOWidth(), patch.getOHeight() ) mapping = TransformMeshMappingWithMasks( mesh ); source = patch.getImageProcessor() if floatp: source = source.convertToFloatProcessor() if interpolate: # patch.getImageProcessor().setInterpolationMethod( ImageProcessor.BILINEAR ) mapping.mapInterpolated( source, target ) else: mapping.map( source, target ) return target
def bunwarpjSingle(impRef, impTarget, landMarks, directTransfoName, inverseTransfoName): directName = 'direct_transformation' inverseName = 'inverse_transformation' impRef.setTitle('bunwarpj_source') impTarget.setTitle('bunwarpj_target') directFileName = os.path.join(saveDir.getAbsolutePath(), directName) inverseFileName = os.path.join(saveDir.getAbsolutePath(), inverseName) #imp = IJ.run(impRef, "bUnwarpJ", "source_image=bunwarpj_source target_image=bunwarpj_target registration=Accurate image_subsample_factor=0 initial_deformation=[Coarse] final_deformation=Fine divergence_weight=0 curl_weight=0 landmark_weight=0.5 image_weight=0.5 consistency_weight=10 stop_threshold=0.01 save_transformations save_direct_transformation=["+ directFileName +"] save_inverse_transformation=["+ inverseFileName +"]"); # transfo = computeTransformationBatch( # param ImagePlus targetImp input target image # param ImagePlus sourceImp input source image # param ImageProcessor targetMskIP target mask # param ImageProcessor sourceMskIP source mask # param int mode accuracy mode (0 - Fast, 1 - Accurate, 2 - Mono) # param int img_subsamp_fact image subsampling factor (from 0 to 7, representing 2^0=1 to 2^7 = 128) # param int min_scale_deformation (0 - Very Coarse, 1 - Coarse, 2 - Fine, 3 - Very Fine) # param int max_scale_deformation (0 - Very Coarse, 1 - Coarse, 2 - Fine, 3 - Very Fine, 4 - Super Fine) # param double divWeight divergence weight # param double curlWeight curl weight # param double landmarkWeight landmark weight # param double imageWeight image similarity weight # param double consistencyWeight consistency weight # param double stopThreshold stopping threshold # return results transformation object accuracy_mode = 1 img_subsamp_fact = 0 tmp = FloatProcessor(impTarget.getWidth(), impTarget.getHeight()) tmp.setValue(1.0) tmp.fill() targetMskIp = tmp.duplicate() sourceMskIp = tmp.duplicate() accuracy_mode = 1 img_subsamp_fact = 0 min_scale_deformation = 1 max_scale_deformation = 2 divWeight = 0.0 curlWeight = 0.0 consistencyWeight = 10 stopThreshold = 0.01 if landMarks == 1: landmarkWeight = 0.5 imageWeight = 0.5 transfo = bUnwarpJ_.computeTransformationBatch( impTarget, impRef, targetMskIp, sourceMskIp, accuracy_mode, img_subsamp_fact, min_scale_deformation, max_scale_deformation, divWeight, curlWeight, landmarkWeight, imageWeight, consistencyWeight, stopThreshold) else: landmarkWeight = 0.0 imageWeight = 1.0 transfo = bUnwarpJ_.computeTransformationBatch( impTarget, impRef, targetMskIp, sourceMskIp, accuracy_mode, img_subsamp_fact, min_scale_deformation, max_scale_deformation, divWeight, curlWeight, landmarkWeight, imageWeight, consistencyWeight, stopThreshold) transfo.saveDirectTransformation(os.path.join(saveDir.getAbsolutePath(), directTransfoName)) transfo.saveInverseTransformation(os.path.join(saveDir.getAbsolutePath(), inverseTransfoName)) #print(transfo.getCoefficients()) return transfo.getInverseResults().getStack().getProcessor(1).duplicate()
def img_calc(func, *imps, **kwargs): """Runs the given function on each pixel of the given list of images. An additional parameter, the title of the result, is passed as keyword parameter. We assume that each image has the same size. This is not checked by this function. """ # If the keyword parameter is not passed, it is set to a default value. if not kwargs['title']: kwargs['title'] = "Result" # This is a 2D list: list[number of images][pixels per image] . pixels = [imp.getProcessor().getPixels() for imp in imps] # The function is called pixel by pixel. # zip(*pixels) rotates the 2D list: list[pixels per image][mumber of images]. result = [func(vals) for vals in zip(*pixels)] # result is a 1D list and can be used to create an ImagePlus object. from ij import ImagePlus from ij.process import FloatProcessor return ImagePlus(kwargs['title'], FloatProcessor(img_size, img_size, result))
def selectionGetCurvature(x, y, n): kernel = [1, 1, 1, 1, 1] x2 = [] y2 = [] for i in range(n): x2.append(x[i]) y2.append(y[i]) ipx = FloatProcessor(n, 1, x, None) ipy = FloatProcessor(n, 1, y, None) ipx.convolve(kernel, len(kernel), 1) ipy.convolve(kernel, len(kernel), 1) indexes = [] curvature = [] for i in range(n): indexes.append(i) curvature.append( float( math.sqrt((x2[i] - x[i]) * (x2[i] - x[i]) + (y2[i] - y[i]) * (y2[i] - y[i])))) return curvature
def identifyTunicate(imp): # Clear ROI manager rm = RoiManager.getInstance() if rm is not None: rm.reset() # Get hue from HSB stack impHue = ProcessHSB.getHue(imp) width = impHue.width height = impHue.height # Get processor ipHue = impHue.getProcessor().convertToFloat() huePixels = ipHue.getPixels() # Get macro hue because it is the same color newPixels = map(ProcessHSB.macroHue, huePixels) ipNew = FloatProcessor(width, height, newPixels) impTunicate = ImagePlus("MacroHue", ipNew) # Bring brightness into the equation impBrightness = ProcessHSB.getBrightness(imp) IJ.run(impBrightness, "Auto Threshold", "method=MaxEntropy white") #IJ.run(impBrightness, "Analyze Particles...", "size=10000-Infinity circularity=0.10-1.00 show=Masks in_situ") # "add" right after "include" to include roi to manager # Logic AND pictures together ic = ImageCalculator() impTunicateMask = ic.run("AND create", impTunicate, impBrightness) IJ.run(impTunicateMask, "8-bit", "") # convert to 8-bit impTunicate.close() impBrightness.close() IJ.run(impTunicateMask, "Analyze Particles...", "size=10000-Infinity circularity=0.50-1.00 show=Masks add in_situ" ) # "add" right after "include" to include roi to manager impTunicateMask.close() #imp.show() #rm = RoiManager.getInstance() #return rm #testImp = IJ.getImage() #result = identifyTunicate(testImp) #print type(result)
def mode_subtract(prj,roi): """ Subtract the mode (calculated over a given ROI) from the image. prj(ImagePlus): a single channel Z-projected ImagePlus object. z_index(int): The central stack number ROI(roi): Region of interest to calculate the mode. """ # Finds mode of a signle stack return the mode from ij.process import FloatProcessor from ij import ImagePlus # Find the mode dmode=roi_mode(prj,roi) imp=prj.duplicate() ip=imp.getProcessor() pix=ip.getPixels() minus_mode= map(lambda x: x - dmode, pix) ip= FloatProcessor(ip.width, ip.height, minus_mode, None) no_noise = ImagePlus(prj.title+"_no-noise", ip) return no_noise
def identifyRed(imp): # Clear ROI manager rm = RoiManager.getInstance() if rm is not None: rm.reset() # set results table # rt = ResultsTable.getResultsTable() # Get hue from HSB stack impHue = ProcessHSB.getHue(imp) width = impHue.width height = impHue.height # Get processor for hue ipHue = impHue.getProcessor().convertToFloat() huePixels = ipHue.getPixels() # Bring brightness into the equation impBrightness = ProcessHSB.getBrightness(imp) IJ.run(impBrightness, "Auto Threshold", "method=MaxEntropy white") IJ.run(impBrightness, "Analyze Particles...", "size=10000-Infinity circularity=0.00-1.00 show=Masks in_situ") # Get processor for brightness ipBrightness = impBrightness.getProcessor().convertToFloat() brightnessPixels = ipBrightness.getPixels() # Do the thing now newPixels = map(ProcessHSB.redHueBackground, brightnessPixels, huePixels) # If hue < 30 and hue > 225, True #newNewPixels = map(ProcessHSB.redHue, newPixels) # Pause: Do this later ipNew = FloatProcessor(width, height, newPixels) impRed = ImagePlus("RedHue", ipNew) IJ.run(impRed, "8-bit", "") # convert to 8-bit #IJ.run(imp, "Options...", "iterations=20 count=1 black do=[Fill Holes]"); impRed.show()
def generate_r_image(imp, ring_rois, centres, unwrap_axis, threshold_val): """for each point in the projection, calculate the distance to the vessel axis and present as an image""" fp = imp.getProcessor() fp.setThreshold(threshold_val, fp.maxValue(), FloatProcessor.NO_LUT_UPDATE) bp = fp.createMask() bp.dilate() bp.erode() mask_imp = ImagePlus("Mask", bp) tile_mask = make_tiled_imp(mask_imp) #tile_mask.show(); #WaitForUserDialog("pasue - generated mask").show(); mask_imp = do_unwrap(tile_mask, unwrap_axis, imp_title=mask_imp.getTitle()) #mask_imp.show(); roi = PolygonRoi([x for (x, y) in unwrap_axis], [y for (x, y) in unwrap_axis], PolygonRoi.POLYLINE) mask_imp.setRoi(roi) #WaitForUserDialog("pasue - unwrapped").show(); IJ.run(mask_imp, "Fill Holes", "") #WaitForUserDialog("pasue - filled holes").show(); IJ.run(mask_imp, "Divide...", "value=255") #WaitForUserDialog("pasue - scaled to 0-1").show(); #mask_imp.show(); r_list = [] for lidx, (roi, centre) in enumerate(zip(ring_rois, centres)): r_sublist = [ math.sqrt((x - centre[0])**2 + (y - centre[1])**2) for x, y in zip(roi.getPolygon().xpoints, roi.getPolygon().ypoints) ] r_list.append(r_sublist) r_imp = ImagePlus("Radii", FloatProcessor([list(x) for x in zip(*r_list)])) tile_r_imp = make_tiled_imp(r_imp) r_imp = do_unwrap(tile_r_imp, unwrap_axis, imp_title=r_imp.getTitle()) r_imp = ImageCalculator().run("Multiply create", r_imp, mask_imp) IJ.run(r_imp, "Cyan Hot", "") return r_imp, mask_imp
def identifyRed(imp): # Clear ROI manager rm = RoiManager.getInstance() if rm is not None: rm.reset() # Get hue from HSB stack impHue = ProcessHSB.getHue(imp) width = impHue.width height = impHue.height # Get processor for hue ipHue = impHue.getProcessor().convertToFloat() huePixels = ipHue.getPixels() # Bring brightness into the equation impBrightness = ProcessHSB.getBrightness(imp) IJ.run(impBrightness, "Auto Threshold", "method=Default white") #IJ.run(impBrightness, "Analyze Particles...", "size=10000-Infinity circularity=0.00-1.00 show=Masks in_situ") # If hue < 30 and hue > 225, True newPixels = map(ProcessHSB.redHue, huePixels) # Pause: Do this later ipNew = FloatProcessor(width, height, newPixels) impRed = ImagePlus("RedHue", ipNew) IJ.run(impRed, "8-bit", "") # convert to 8-bit # Logic AND pictures together ic = ImageCalculator() impRedMask = ic.run("AND create", impRed, impBrightness) IJ.run(impRedMask, "8-bit", "") # convert to 8-bit IJ.run(impRedMask, "Analyze Particles...", "size=10000-Infinity circularity=0.00-1.00 show=Masks add in_situ") # "add" right after "include" to include roi to manager impHue.close() impBrightness.close() impRed.close() impRedMask.close()
def depthmap(stack): # Takes a single channel z stack. width = stack.getWidth() height = stack.getHeight() # Loop through slices in stack. size = stack.getSize() outstack = ImageStack() IJ.log("size: {}".format(size)) for z in range(1, size): # Calculate maxfilter. imslice = stack.getPixels(z) imslice = [i for i in imslice] imslice = FloatProcessor(width, height, imslice) imslice = maxfilter(imslice) outstack.addSlice(imslice) IJ.showProgress(1.0*z/size) # Return output stack. return outstack
def projectfocus(instack, depthstack): # Initialize variables. width = instack.getWidth() height = instack.getHeight() nSlices = instack.getSize() dest_pixels = [0] * width * height # Loop through y coordinates. for y in range(height): offset = y*width # Loop through x coordinates for x in range(width): i = offset + x maxpx = 0.0 maxslice = 1 # Loop through z stack. for z in range(1, nSlices): # Find maximum pixel value current_pixels = depthstack.getPixels(z) current_pix = current_pixels[i] if current_pix > maxpx: maxslice = z maxpx = current_pix origin_pixels = instack.getPixels(maxslice) # origin_pixels = [((i+min(origin_pixels))/max(origin_pixels))*255 for i in origin_pixels]# Need to get rid of negative pixels! dest_pixels[i] = origin_pixels[i] output = FloatProcessor(width, height, dest_pixels) return output
def bunwarpjSingle(impRef, impTarget, landMarks, directTransfoName, inverseTransfoName): directName = 'direct_transformation' inverseName = 'inverse_transformation' impRef.setTitle('bunwarpj_source') impTarget.setTitle('bunwarpj_target') directFileName = os.path.join(saveDir.getAbsolutePath(), directName) inverseFileName = os.path.join(saveDir.getAbsolutePath(), inverseName) #imp = IJ.run(impRef, "bUnwarpJ", "source_image=bunwarpj_source target_image=bunwarpj_target registration=Accurate image_subsample_factor=0 initial_deformation=[Coarse] final_deformation=Fine divergence_weight=0 curl_weight=0 landmark_weight=0.5 image_weight=0.5 consistency_weight=10 stop_threshold=0.01 save_transformations save_direct_transformation=["+ directFileName +"] save_inverse_transformation=["+ inverseFileName +"]"); # transfo = computeTransformationBatch( # param ImagePlus targetImp input target image # param ImagePlus sourceImp input source image # param ImageProcessor targetMskIP target mask # param ImageProcessor sourceMskIP source mask # param int mode accuracy mode (0 - Fast, 1 - Accurate, 2 - Mono) # param int img_subsamp_fact image subsampling factor (from 0 to 7, representing 2^0=1 to 2^7 = 128) # param int min_scale_deformation (0 - Very Coarse, 1 - Coarse, 2 - Fine, 3 - Very Fine) # param int max_scale_deformation (0 - Very Coarse, 1 - Coarse, 2 - Fine, 3 - Very Fine, 4 - Super Fine) # param double divWeight divergence weight # param double curlWeight curl weight # param double landmarkWeight landmark weight # param double imageWeight image similarity weight # param double consistencyWeight consistency weight # param double stopThreshold stopping threshold # return results transformation object accuracy_mode = 1 img_subsamp_fact = 0 tmp = FloatProcessor(impTarget.getWidth(), impTarget.getHeight()) tmp.setValue(1.0) tmp.fill() targetMskIp = tmp.duplicate() sourceMskIp = tmp.duplicate() accuracy_mode = 1 img_subsamp_fact = 0 min_scale_deformation = 1 max_scale_deformation = 2 divWeight = 0.0 curlWeight = 0.0 consistencyWeight = 10 stopThreshold = 0.01 if landMarks == 1: landmarkWeight = 0.5 imageWeight = 0.5 transfo = bUnwarpJ_.computeTransformationBatch( impTarget, impRef, targetMskIp, sourceMskIp, accuracy_mode, img_subsamp_fact, min_scale_deformation, max_scale_deformation, divWeight, curlWeight, landmarkWeight, imageWeight, consistencyWeight, stopThreshold) else: landmarkWeight = 0.0 imageWeight = 1.0 transfo = bUnwarpJ_.computeTransformationBatch( impTarget, impRef, targetMskIp, sourceMskIp, accuracy_mode, img_subsamp_fact, min_scale_deformation, max_scale_deformation, divWeight, curlWeight, landmarkWeight, imageWeight, consistencyWeight, stopThreshold) transfo.saveDirectTransformation( os.path.join(saveDir.getAbsolutePath(), directTransfoName)) transfo.saveInverseTransformation( os.path.join(saveDir.getAbsolutePath(), inverseTransfoName)) #print(transfo.getCoefficients()) return transfo.getInverseResults().getStack().getProcessor(1).duplicate()
jDD = SM(K, K).eqInnerProductMatrix(jD) jMP = MP(jD, jDD) # matching pursuit to create a sparse appoximation w = [] for i in range(0, p): q = x[i] if Rt == "OMP": W = jMP.vsOMP(q, t_w) elif Rt == "MP": W = jMP.vsBMP(q, t_w) else: W = jMP.vsORMP(q, t_w) w.append(W) w2 = zip(*w) Sp = Matrix(w2).getColumnPackedCopy() #return matrices to images ipFloat = FloatProcessor(K, imp2.height * imp2.width, Sp) impa = ImagePlus("Sp", ipFloat) impa.show() IJ.run("Montage to Stack...", "columns=1 rows=" + str(imp2.height) + " border=0") imp3 = IJ.getImage() IJ.run("Reslice [/]...", "output=1.000 start=Left avoid") impa.close() imp3.close()
def fretCalculations(imp1, nFrame, donorChannel, acceptorChannel, acceptorChannel2, table, gfx1, gfx2, gfx3, gfx4, gfx5, originalTitle): donorImp = extractChannel(imp1, donorChannel, nFrame) acceptorImp = extractChannel(imp1, acceptorChannel, nFrame) acceptorImp2 = extractChannel(imp1, acceptorChannel2, nFrame) #push donor and acceptor channels to gpu and threshold them both to remove saturated pixels gfx4 = clij2.push(donorImp) gfx5 = clij2.push(acceptorImp) gfx6 = clij2.create(gfx5) clij2.threshold(gfx4, gfx2, maxIntensity) clij2.binarySubtract(gfx3, gfx2, gfx6) clij2.threshold(gfx5, gfx2, maxIntensity) clij2.binarySubtract(gfx6, gfx2, gfx3) clij2.threshold(gfx3, gfx6, 0.5) clij2.multiplyImages(gfx6, gfx4, gfx2) clij2.multiplyImages(gfx6, gfx5, gfx4) gfx6 = clij2.push(acceptorImp2) #donor is gfx2, acceptor FRET is gfx4, segment channel (acceptor normal) is gfx6 results = ResultsTable() clij2.statisticsOfBackgroundAndLabelledPixels(gfx2, gfx1, results) donorChIntensity = results.getColumn(13) results2 = ResultsTable() clij2.statisticsOfBackgroundAndLabelledPixels(gfx4, gfx1, results2) acceptorChIntensity = results2.getColumn(13) results3 = ResultsTable() clij2.statisticsOfBackgroundAndLabelledPixels(gfx6, gfx1, results3) #calculate the fret ratios, removing any ROI with intensity of zero FRET = [] for i in xrange(len(acceptorChIntensity)): if (acceptorChIntensity[i] > 0) and (donorChIntensity[i] > 0): #don't write in the zeros to the results FRET.append((1000 * acceptorChIntensity[i] / donorChIntensity[i])) table.incrementCounter() table.addValue("Frame (Time)", nFrame) table.addValue("Label", i) table.addValue("Emission ratio", acceptorChIntensity[i] / donorChIntensity[i]) table.addValue("Mean donor emission", results.getValue("MEAN_INTENSITY", i)) table.addValue("Mean acceptor emission (FRET)", results2.getValue("MEAN_INTENSITY", i)) table.addValue("Mean acceptor emission", results3.getValue("MEAN_INTENSITY", i)) table.addValue("Sum donor emission", donorChIntensity[i]) table.addValue("Sum acceptor emission (FRET)", acceptorChIntensity[i]) table.addValue("Sum acceptor emission", results3.getValue("SUM_INTENSITY", i)) table.addValue( "Volume", cal.pixelWidth * cal.pixelHeight * cal.pixelDepth * results.getValue("PIXEL_COUNT", i)) table.addValue("Pixel count", results.getValue("PIXEL_COUNT", i)) table.addValue("x", cal.pixelWidth * results.getValue("CENTROID_X", i)) table.addValue("y", cal.pixelHeight * results.getValue("CENTROID_Y", i)) table.addValue("z", cal.pixelDepth * results.getValue("CENTROID_Z", i)) table.addValue("File name", originalTitle) else: #must write in the zeros as this array is used to generate the map of emission ratios FRET.append(0) table.show("Results of " + originalTitle) FRET[0] = 0 FRETarray = array("f", FRET) fp = FloatProcessor(len(FRET), 1, FRETarray, None) FRETImp = ImagePlus("FRETImp", fp) gfx4 = clij2.push(FRETImp) clij2.replaceIntensities(gfx1, gfx4, gfx5) maxProj = clij2.create(gfx5.getWidth(), gfx5.getHeight(), 1) clij2.maximumZProjection(gfx5, maxProj) #pull the images FRETimp2 = clij2.pull(gfx5) FRETProjImp = clij2.pull(maxProj) labelImp = clij2.pull(gfx1) clij2.clear() donorImp.close() acceptorImp.close() acceptorImp2.close() return table, FRETimp2, FRETProjImp, labelImp
def do_angular_projection(imp, max_r_pix=60, min_r_pix=10, generate_roi_stack=True): """perform ray-based projection of vessel wall, c.f. ICY TubeSkinner (Lancino 2018)""" Prefs.blackBackground = True print("do angular projection input imp = " + str(imp)) split_chs = ChannelSplitter().split(imp) mch_imp = split_chs[0] IJ.setAutoThreshold(mch_imp, "IsoData dark stack") egfp_imp = split_chs[1] proj_imp = Duplicator().run(egfp_imp) cl_imp = split_chs[2] if generate_roi_stack: egfp_imp_disp = Duplicator().run(egfp_imp) roi_stack = IJ.createImage("rois", egfp_imp.getWidth(), egfp_imp.getHeight(), egfp_imp.getNSlices(), 16) centres = [] projected_im_pix = [] ring_rois = [] for zidx in range(cl_imp.getNSlices()): if ((zidx + 1) % 100) == 0: print("Progress = " + str(round(100 * (float(zidx + 1) / cl_imp.getNSlices())))) projected_im_row = [] proj_imp.setZ(zidx + 1) mch_imp.setZ(zidx + 1) bp = mch_imp.createThresholdMask() bp.dilate() bp.erode() bp.erode() bp.erode() mask_imp = ImagePlus("mask", bp) IJ.run(mask_imp, "Create Selection", "") roi = mask_imp.getRoi() proj_imp.setRoi(roi) IJ.run(proj_imp, "Set...", "value=0 slice") IJ.run(proj_imp, "Make Inverse", "") roi = proj_imp.getRoi() centre = (roi.getStatistics().xCentroid, roi.getStatistics().yCentroid) centres.append(centre) ring_roi_xs = [] ring_roi_ys = [] for theta in range(360): pt1 = (centre[0] + min_r_pix * math.cos(math.radians(theta)), centre[1] + min_r_pix * math.sin(math.radians(theta))) pt2 = (centre[0] + max_r_pix * math.cos(math.radians(theta)), centre[1] + max_r_pix * math.sin(math.radians(theta))) roi = Line(pt1[0], pt1[1], pt2[0], pt2[1]) proj_imp.setRoi(roi) profile = roi.getPixels() projected_im_row.append(max(profile)) try: ring_roi_xs.append(roi.getContainedPoints()[profile.index( max(profile))].x) except IndexError: ring_roi_xs.append(pt2[0]) try: ring_roi_ys.append(roi.getContainedPoints()[profile.index( max(profile))].y) except IndexError: ring_roi_ys.append(pt2[1]) proj_imp.killRoi() ring_roi = PolygonRoi(ring_roi_xs, ring_roi_ys, Roi.FREELINE) ring_rois.append(ring_roi) if generate_roi_stack: roi_stack.setZ(zidx + 1) roi_stack.setRoi(ring_roi) IJ.run(roi_stack, "Line to Area", "") IJ.run( roi_stack, "Set...", "value=" + str(roi_stack.getProcessor().maxValue()) + " slice") #egfp_imp.setRoi(ring_roi); projected_im_pix.append(projected_im_row) # for ch in split_chs: # ch.close(); out_imp = ImagePlus( "projected", FloatProcessor([list(x) for x in zip(*projected_im_pix)])) if generate_roi_stack: roi_stack.show() egfp_imp_disp.show() # merge? else: roi_stack = None return out_imp, roi_stack, ring_rois, centres
# 밑바닥부터 이미지 만들기 from ij import ImagePlus from ij.process import FloatProcessor from array import zeros from random import random width = 1024 height = 1024 # Jython으로 array 만들기 # http://fiji.sc/wiki/index.php/Jython_Scripting_Examples#Creating_multi-dimensional_native_java_arrays pixels = zeros('f', width * height) # f: "float" for i in xrange(len(pixels)): pixels[i] = random() fp = FloatProcessor(width, height, pixels, None) imp = ImagePlus("White noise", fp) imp.show()
dzdx.close() Norms.setSlice(2) dzdy = Norms.crop() dzdy.show() dzdy = IJ.getImage() IJ.run("FFT") #Needs to be a complex Fourier transform DZDY = IJ.getImage() dzdy.close() # Create two images with a ramp gradient from left to right (wx and wy in Frankot Chellapa). # Size of ramp needs to be a square of same dimensions as FFT image generated by ImageJ. # Make sure that "Complex Fourier Transform" button under "Process, FFT" is selected or else it will not work... imp = ImagePlus( "wx", FloatProcessor(1024, 1024) ) # for later create a dialog box for choosing pads of 512x512, 1024x1024, 2048x2048, etc. pix = imp.getProcessor().getPixels() n_pixels = len(pix) # total number of pixels w = imp.getWidth() # length of one row for i in range( len(pix) ): # fill row with linear ramp from 0 to whatever the image width; for 512 size, values range 0 to 512 pix[i] = i % w imp.getProcessor() imp.show() imp = IJ.getImage() #adjust min and max so the ramp ranges from -0.5 cycles/pixel to + 0.5 cycles/pixel
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() new_blue = FloatProcessor(imp.width, imp.height) pix_new_blue = new_blue.getPixels() new_blade = FloatProcessor(imp.width, imp.height) pix_blade = new_blade.getPixels() for k in range(len(pix_red)): if (pix_green[k] > 100) & (pix_green[k] < 250) & (pix_red[k] < 250) & (pix_blue[k] < 250): pix_new_red[k] = pix_red[k] pix_new_green[k] = pix_green[k]
del pix2 del pix3 del pix4 if not os.path.exists(subsub): os.mkdir(subsub) pixels = [] for j in range(4): System.gc() imp = segmentator.applyClassifier(imps[j], 0, True) imp = imp.getStack() imp = imp.getProcessor(1) cm = imp.getColorModel() pixels.append(imp.getPixels()) pix1 = pixels[0] pix2 = pixels[1] pix3 = pixels[2] pix4 = pixels[3] pixcomb = pix1[:-s * d1] + pix2[s * d1:-s * d1] + pix3[s * d1:-s * d1] + pix4[s * d1:] result = ImagePlus("Result", FloatProcessor(d1, dimentions[1], pixcomb, cm)) IJ.save(result, subsub + "\\result_RAW.tif") IJ.run(result, "Despeckle", "") strel = morphology.Strel.Shape.DISK.fromDiameter(3) result = morphology.Morphology.erosion(result.getProcessor(), strel) result = result.convertToByteProcessor() result = ImagePlus("plus", result) IJ.run(result, "Gaussian Blur...", "sigma=15") IJ.save(result, subsub + "\\result_READY.tif") result.close()
def do_tubefitting(im_path=im_test_path, metadata_path=metadata_test_path, output_path=output_path, save_output=False): # todo: fix things so that all operations use a consistent definition of background rather than changing Prefs on the fly... Prefs.blackBackground = False info = PrescreenInfo() info.load_info_from_json(metadata_path) z_xy_ratio = abs( info.get_z_plane_spacing_um()) / info.get_xy_pixel_size_um() #z_xy_ratio = 1.0; bfimp = bf.openImagePlus(im_path) imp = bfimp[0] imp.show() IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") imp = utils.downsample_for_isotropy(imp, extra_downsample_factor=1.0, info=info) rot_seg_imp, rot_proj_imp, egfp_mch_imps = split_and_rotate(imp, info) depth = rot_seg_imp.getNSlices() if rot_seg_imp.getNSlices( ) > rot_seg_imp.getNFrames() else rot_seg_imp.getNFrames() width = rot_seg_imp.getWidth() height = int(round(rot_seg_imp.getHeight() * z_xy_ratio)) # Apply 3d MEDIAN FILTER to denoise and emphasise vessel-associated voxels fit_basis_imp = threshold_and_binarise(rot_seg_imp, z_xy_ratio) fit_basis_imp.setTitle("fit_basis_imp") fit_basis_imp.show() # plane-wise, use binary-outline # say the non-zero points then make up basis for fitting to be performed per http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html rois = [] centres = [] major_axes = [] roi_imp = IJ.createImage("rois", width, height, depth, 32) pts_stack = ImageStack(width, height + 1) IJ.run(imp, "Line Width...", "line=3") for zidx in range(fit_basis_imp.getNSlices()): fit_basis_imp.setZ(zidx + 1) IJ.run(fit_basis_imp, "Outline", "slice") IJ.run(fit_basis_imp, "Create Selection", "") roi = fit_basis_imp.getRoi() fit_basis_imp.killRoi() pts = [(pt.x, pt.y) for pt in roi.getContainedPoints()] clean_pts = convex_hull_pts(pts) clean_pts = [(x, z_xy_ratio * y) for (x, y) in clean_pts] # make a stack of clean points... ip = FloatProcessor(width, height + 1) pix = ip.getPixels() for pt in clean_pts: pix[int(pt[1]) * width + int(pt[0])] = 128 pts_stack.addSlice(ip) centre, angle, axl = ellipse_fitting.fit_ellipse(clean_pts) major_axes.append(max(axl)) centres.append(centre) rot_seg_imp.setZ(zidx + 1) ellipse_roi = ellipse_fitting.generate_ellipse_roi(centre, angle, axl) rois.append(ellipse_roi) IJ.run(imp, "Line Width...", "line=1") cal = imp.getCalibration() smooth_centres, tangent_vecs = generate_smoothed_vessel_axis( centres, pixel_size_um=cal.pixelDepth) for zidx in range(fit_basis_imp.getNSlices()): centre = smooth_centres[zidx] major_axis = major_axes[zidx] ellipse_roi = EllipseRoi(centre[0] - 2, centre[1], centre[0] + 2, centre[1], 1.0) roi_imp.setZ(zidx + 1) roi_imp.setRoi(ellipse_roi) IJ.run(roi_imp, "Set...", "value=" + str(roi_imp.getProcessor().maxValue()) + " slice") pts_stack_imp = ImagePlus("Cleaned points", pts_stack) pts_stack_imp.setTitle("pts_stack_imp") pts_stack_imp.show() rot_seg_imp.changes = False rot_seg_imp.close() egfp_imp = egfp_mch_imps[0] mch_imp = egfp_mch_imps[1] imps_to_combine = [egfp_mch_imps[1], egfp_mch_imps[0], roi_imp] egfp_imp.show() mch_imp.show() roi_imp.show() print("box height um = " + str(roi_imp.getNSlices() * info.get_xy_pixel_size_um())) IJ.run( egfp_imp, "Size...", "width=" + str(width) + " height=" + str(height) + " depth=" + str(depth) + " average interpolation=Bilinear") IJ.run( mch_imp, "Size...", "width=" + str(width) + " height=" + str(height) + " depth=" + str(depth) + " average interpolation=Bilinear") #IJ.run("Merge Channels...", "c1=[" + mch_imp.getTitle() + # "] c2=[" + egfp_imp.getTitle() + # "] c7=[" + roi_imp.getTitle() + "] create keep"); composite_imp = RGBStackMerge().mergeChannels(imps_to_combine, False) print(composite_imp) composite_imp.show() print("end of vessel centerline id step, image dims = ({}x{}x{})".format( composite_imp.getWidth(), composite_imp.getHeight(), composite_imp.getNSlices())) WaitForUserDialog("pause").show() # do qc here? #WM.getImage("Composite").addImageListener(UpdateRoiImageListener(rois)); IJ.run(roi_imp, "8-bit", "") if save_output: FileSaver(composite_imp).saveAsTiffStack( os.path.join(output_path, "segmentation result.tif")) print(roi_imp) FileSaver(roi_imp).saveAsTiff( os.path.join(output_path, "vessel axis.tif")) egfp_imp.changes = False mch_imp.changes = False roi_imp.changes = False fit_basis_imp.changes = False pts_stack_imp.changes = False egfp_imp.close() mch_imp.close() #roi_imp.close(); fit_basis_imp.close() pts_stack_imp.close() zcoords = [i for i in range(composite_imp.getNSlices())] xyz_smooth_centres = [(x, y, z) for ((x, y), z) in zip(smooth_centres, zcoords)] composite_imp2 = straighten_vessel(composite_imp, xyz_smooth_centres, save_output=True) composite_imp3 = straighten_vessel(composite_imp2, xyz_smooth_centres, it=2, save_output=True) return composite_imp3
#Import XYZ Images. Normalize by white balance before. n_slices = imp2.getStack().getSize() I =[] for i in range(1, n_slices+1): imp2.setSlice(i) n = imp2.getProcessor().getPixels() n2 = [val for val in n] I.append(n2) D= SimpleMatrix(I) RGB = M.mult(D).getMatrix().data L1 = [RGB[i:i+imp2.height*imp2.width] for i in range(0, len(RGB), imp2.height*imp2.width)] #fiddly bits to make an image stack and display R = ImagePlus("Red", FloatProcessor(imp2.width,imp2.height,L1[0])).show() G= ImagePlus("Green", FloatProcessor(imp2.width,imp2.height,L1[1])).show() B = ImagePlus("Blue", FloatProcessor(imp2.width,imp2.height,L1[2])).show() IJ.run("Images to Stack", "name=Stack title=[] use") imp = IJ.getImage() imp.setTitle("RGB") IJ.run("Make Composite", "display=Composite") IJ.run("Enhance Contrast", "saturated=0.35") IJ.run("Next Slice [>]") IJ.run("Enhance Contrast", "saturated=0.35") IJ.run("Next Slice [>]") IJ.run("Enhance Contrast", "saturated=0.35")
#imp1=dsin.duplicate() #imp = ij.convert().convert(imp1, ImagePlus) imp = ImagePlus() imp.setDimensions(c, z, 1) stack = ImageStack(h, w) #imp1.copyDataFrom(dsin) k = 0 ioffset = 0 planesize = h * w for i in range(0, z): for j in range(0, c): k = k + 1 stack.addSlice( str(k), FloatProcessor(h, w, doutarray[ioffset:(ioffset + planesize)])) ioffset = ioffset + planesize #outds1 = ijmService.getDataset(doutMNarray) imp.setStack(stack, c, z, 1) if c == 2: outds1 = extractChannel(imp, 1, 2) outds2 = extractChannel(imp, 2, 2) # outds1 = createChannel(doutarray,h,w,z,1) # outds2 = createChannel(doutarray,h,w,z,2) outds1.setColor(java.awt.Color.RED) outds2.setColor(java.awt.Color.GREEN) outds = RGBStackMerge.mergeChannels(array([outds1, outds2], ImagePlus), 0) else: if c > 2: outds1 = extractChannel(imp, 1, 3)
from ij.process import ImageStatistics, AutoThresholder from ij.process.AutoThresholder import getThreshold from ij.process.AutoThresholder import Method from script.imglib.math import Compute, Divide, Multiply, Subtract from script.imglib.algorithm import Gauss, Scale2D, Resample from script.imglib import ImgLib import mpicbg.imglib.image.ImagePlusAdapter import mpicbg.imglib.image.display.imagej.ImageJFunctions import fiji.process.Image_Expression_Parser IJ.run("Close All") imp = ImagePlus("my new image", FloatProcessor(512, 512)) pix = imp.getProcessor().getPixels() print(type(pix)) n_pixels = len(pix) print(n_pixels) # catch width w = imp.getWidth() # create a ramp gradient from left to right for i in range(len(pix)): pix[i] = i % w # adjust min and max, since we know them imp.getProcessor().setMinAndMax(0, w-1) imp.show()
# 이미지 전체에서 최소픽셀값 빼기 from ij import IJ, ImagePlus from ij.process import FloatProcessor imp = IJ.getImage() ip = imp.getProcessor().convertToFloat() # as a copy pixels = ip.getPixels() # Built-in 함수 사용 (min, reduce) # pixels를 훑으며 min 적용 minimum = reduce(min, pixels) # Method 1: for loop을 적용해서 모든 pixel 값을 직접 변경 for i in xrange(len(pixels)): pixels[i] -= minimum # 변경된 pixel값들로 새 이미지 만들기: imp2 = ImagePlus(imp.title, ip) # Method 2: 모든 pixel에서 최소값을 뺀 결과를 다른 배열(pixel3)에 저장 pixels3 = map(lambda x: x - minimum, pixels) # 배열로부터 이미지 만들기 ip3 = FloatProcessor(ip.width, ip.height, pixels3, None) # None: color imp3 = ImagePlus(imp.title, ip3) # Show the images in an ImageWindow: imp2.show() imp3.show()
# Input parameters N = 500 # number of pixels L = 532 * 0.000000001 # wavelength in nm w = 0.002 # width of field in meters z = 0.05 # object-to-detector distance in meter imp = IJ.getImage() z = Propagator.Zone(L, N, z, w) #wave propagation term #iterative reconstruction for j in range(0, 50): if j == 0: #creating initial complex-valued field distribution in the detector plane imp_init = ImagePlus("real", FloatProcessor(N, N, [0 for i in range(N * N)])) fft_1 = fft.fft(imp, imp_init, N, N) else: #reconstruction of transmission function imp2 = ImagePlus( "phase", FloatProcessor(N, N, [cmath.phase(x) for x in fft_4], None)) m = [val for val in imp.getProcessor().getPixels()] sin = [math.sin(val) for val in imp2.getProcessor().getPixels()] cos = [math.cos(val) for val in imp2.getProcessor().getPixels()] imp_r = ImagePlus( "", FloatProcessor(N, N, [x * y for x, y in zip(m, cos)])) imp_i = ImagePlus( "", FloatProcessor(N, N, [x * y for x, y in zip(m, sin)])) fft_1 = fft.fft(imp_r, imp_i, N, N)
# 선택 영역 칠하기 from ij import ImagePlus from ij.process import FloatProcessor from array import zeros from random import random from ij.gui import Roi, PolygonRoi # noise로 칠해진 이미지 생성 width = 1024 height = 1024 pixels = zeros('f', width * height) for i in xrange(len(pixels)): pixels[i] = random() fp = FloatProcessor(width, height, pixels, None) imp = ImagePlus("Random", fp) imp.show() # 직사각형 관심영역(ROI: Region of Interest)를 2로 채우기 fp = FloatProcessor(width, height, pixels, None) roi = Roi(400, 200, 400, 300) # Roi(int x, int y, int width, int height) fp.setRoi(roi) fp.setValue(2.0) fp.fill() imp2 = ImagePlus("Rectangle", fp) imp2.show() # Polygon ROI를 -3으로 채우기
# open image (RGB) imp = IJ.openImage(srcpath) # imageProcessor ip = imp.getProcessor() # FloatProcessor by channel chpx = [] # channel pixels filtered = [] # filtered FloatProcessor for i in range(3): chpx.append(ip.toFloat(i, None).getPixels()) _filtered = [threshold(p) for p in chpx[i]] # filtered pixels filtered.append(FloatProcessor(ip.width, ip.height, _filtered, None)) # save each channels for i in range(3): IJ.save(ImagePlus("filtered_%d" % i, filtered[i]), dstpath[:-4] + '_%d' % i) # add slices to new stack stack_new = ImageStack(imp.width, imp.height) for i in range(3): stack_new.addSlice(None, filtered[i]) # new image (stack) imp_new = ImagePlus("new", stack_new) imp_new.show()
IJ.run(roi_stack, "Set...", "value=" + str(roi_stack.getProcessor().maxValue()) + " slice") min_idx = projected_im_row.index(min(projected_im_row)) # print("min idx = " + str(min_idx)); unzip_axis.append(min_idx) egfp_imp.setRoi(ring_roi) projected_im_pix.append(projected_im_row) # WaitForUserDialog("pause").show(); #print(centres); for ch in split_chs: ch.close() w = len(projected_im_row) h = len(projected_im_pix) ip = FloatProcessor(w, h) pix = ip.getPixels() for x in range(w): for y in range(h): pix[y * w + x] = projected_im_pix[y][x] out_imp = ImagePlus("projected", ip) out_imp.show() egfp_imp_disp.show() roi_stack.show() #egfp_imp_disp.addImageListener(UpdateRoiImageListener(ring_rois)); unwrapped_imp = IJ.createImage("twisted unwrap", 2 * out_imp.getWidth(), out_imp.getHeight(), 1, 32) unwrapped_imp.show()
calc.calculate("Add create", red,green); IJ.run("Subtract Background...", "rolling=50"); IJ.run("LoG 3D"); imp = IJ.getImage() pix = imp.getProcessor().convertToFloat().getPixels() # find out the minimal pixel value min = reduce(Math.min, pix) # create a new pixel array with the minimal value subtracted pix2 = map(lambda x: x - min, pix) name="log" ImagePlus(name, FloatProcessor(imp.width, imp.height, pix2, None)).show() IJ.run("16-bit"); IJ.selectWindow(name) IJ.run("16-bit") IJ.run("Auto Threshold", "method=Otsu"); '''IJ.run("Make Binary"); table = ResultsTable() # Create a hidden ROI manager, to store a ROI for each blob or cell roim = RoiManager(True) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 0, Double.POSITIVE_INFINITY, 0.0, 1.0) print len(table)'''
# reshape image stack as an n x m matrix n_slices = imp2.getStack().getSize() I = [] for i in range(1, n_slices + 1): imp2.setSlice(i) n = imp2.getProcessor().getPixels() n2 = [val for val in n] I.append(n2) # construct Jama matrices and calculate normals B = Matrix(L) C = Matrix(I) kN = B.solve(C).getColumnPackedCopy() # calculate normals via least squares #return matrices to images ipFloat = FloatProcessor(3, imp2.height * imp2.width, kN) impa = ImagePlus("kN", ipFloat) impa.show() #reshape as using montage and reslice commands (need a better way to do this) IJ.run(impa, "Montage to Stack...", "images_per_row=1 images_per_column=%d border=0" % imp2.height) impb = IJ.getImage() IJ.run("Reslice [/]...", "output=1.000 start=Left avoid") impc = IJ.getImage() impa.close() impb.close() #calculating albedo IJ.run("Z Project...", "projection=[Max Intensity]")
A speed test example fixed Modifications Date Who Ver What ---------- --- ------ ------------------------------------------------- 2017-04-02 JRM 0.1.00 Initial test with 4096. Original example did not import functions. 11.594sec on jrmFastMac """ from org.python.core import codecs codecs.setDefaultEncoding('utf-8') from java.lang import System from ij import IJ, ImagePlus from ij.process import FloatProcessor from math import sqrt t0 = System.currentTimeMillis() size = 4096 ip = FloatProcessor(size,size) for y in range(size): IJ.showProgress(y,size-1) for x in range(size): dx=x-size/2; dy=y-size/2 d = sqrt(dx*dx+dy*dy) ip.setf(x,y,-d) time = str((System.currentTimeMillis()-t0)/1000.0)+" seconds" ImagePlus(time,ip).show() IJ.run("Red/Green");
def maxfilter(floatIm, kernalSize=11): def _kernalmax(floatIm, X, Y, kernalX, kernalY): # Define image dimensions and kernal shape. pixels_ = floatIm.getPixels() width_ = int(floatIm.getWidth()) height_ = int(floatIm.getHeight()) halfX = int(kernalX / 2) halfY = int(kernalY / 2) startX = int(X-halfX) startY = int(Y-halfY) if (startX < 0): startX = 0 if (startY < 0): startY = 0 endX = X+halfX endY = Y+halfY if (endX > width_): endX = width_ if (endY > height_): endY = height_ # Loop through y coordinates, shift kernal for every pixel. maxPx = 0 for y in range(startY, endY): offset_ = width_ * y for x in range(startX, endX): j = offset_ + x if pixels_[j] > maxPx: maxPx = pixels_[j] return maxPx # Define input image dimensions. width = floatIm.getWidth() height = floatIm.getHeight() ndim = width * height # pixels = floatIm.getPixels() # pixIn = [pixels[i] for i in range(len(pixels))] # Initiate output stack with same XY dimensions as input stack. pixOut = [0] * ndim # Calculate Sobel transform of input image. procIm = floatIm.convertToByteProcessor(True) # procIm = procIm.medianFilter() # procIm = procIm.smooth() # procIm = procIm.findEdges() # Loop through pixels in y dimension. for row in range(height-1): offset = width * row # Within every y dimension, loop through pixels in x dimension. for column in range(width-1): # Retrieve maximum within kernel around pixel in sobel filtered image. # Set pixel value in output to max of kernel in sobel image. i = offset + column pixOut[i] = _kernalmax(procIm, column, row, kernalSize, kernalSize) # Return floatOut = FloatProcessor(width, height, pixOut) return floatOut
from ij import IJ, ImagePlus, WindowManager from ij.process import FloatProcessor from ij.gui import OvalRoi, Roi from ij.plugin.filter import GaussianBlur from java.util import Random w, h = 128, 128 fp = FloatProcessor(w, h) imp = ImagePlus("synth training", fp) fp.setColor(150) # background fp.fill() # neurites rois = [ OvalRoi(w / 2 - w / 4, h / 2 - h / 4, w / 4, h / 2), # stretched vertically OvalRoi(w / 2, h / 2 - h / 8, w / 4, h / 4), OvalRoi(w / 2 - w / 18, h / 2 + h / 10, w / 6, h / 4), OvalRoi(w / 2 - w / 18, h / 8 + h / 16, w / 3, h / 5) ] fp.setColor(50) # membrane fp.setLineWidth(3) for roi in rois: fp.draw(roi) fp.setColor(90) # oblique membrane fp.setLineWidth(5) roi_oblique = OvalRoi(w / 2 + w / 8, h / 2 + h / 8, w / 4, h / 4)
# from ij import IJ, ImagePlus from ij.process import FloatProcessor from array import zeros from random import random from ij.gui import Roi, PolygonRoi # Create a new ImagePlus filled with noise width = 1024 height = 1024 pixels = zeros('f', width * height) for i in xrange(len(pixels)): pixels[i] = random() fp = FloatProcessor(width, height, pixels, None) imp = ImagePlus("Random", fp) # Fill a rectangular region of interest # with a value of 2: roi = Roi(400, 200, 400, 300) fp.setRoi(roi) fp.setValue(2.0) fp.fill() # Fill a polygonal region of interest # with a value of -3 xs = [234, 174, 162, 102, 120, 123, 153, 177, 171, 60, 0, 18, 63, 132, 84, 129, 69, 174, 150, 183, 207, 198, 303, 231, 258, 234, 276, 327, 378, 312, 228, 225, 246, 282, 261, 252]
def regBf(fn=None, imp=None, refId=None): """ Register a time series stack to a specified reference slice, from a file (imported by BioFormat) or a stack ImagePlus. Returns a registered ImagePlus. The stack must have only 1 z layer. refId is in the format of [int channel, int slice, int frame] If no refId is supplied, will use the first slice [1,1,1] Note: since TurboReg is used for registeration, there will be temporary opened image windows. """ ## Prepare the right ImagePlus if imp is None: if fn is None: od = OpenDialog("Choose a file", None) filename = od.getFileName() if filename is None: print "User canceled the dialog!" return else: directory = od.getDirectory() filepath = directory + filename print "Selected file path:", filepath else: if os.path.exists(fn) and os.path.isfile(fn): filepath = fn else: print "File does not exist!" return imps = BF.openImagePlus(filepath) imp = imps[0] if imp is None: print "Cannot load file!" return else: if fn is not None: print "File or ImagePlus? Cannot load both." return width = imp.getWidth() height = imp.getHeight() # C nChannels = imp.getNChannels() # Z nSlices = imp.getNSlices() # T nFrames = imp.getNFrames() # pixel size calibration = imp.getCalibration() # Only supoort one z layer if nSlices != 1: print "Only support 1 slice at Z dimension." return # set registration reference slice if refId is None: refC = 1 refZ = 1 refT = 1 else: refC = refId[0] refZ = refId[1] refT = refId[2] if (refC not in range(1, nChannels + 1) or refZ not in range(1, nSlices + 1) or refT not in range(1, nFrames + 1)): print "Invalid reference image!" return stack = imp.getImageStack() registeredStack = ImageStack(width, height, nChannels * nFrames * nSlices) # setup windows, these are needed by TurboReg tmpip = FloatProcessor(width, height) refWin = ImageWindow(ImagePlus("ref", tmpip)) bounds = refWin.getBounds() # refWin.setVisible(False) toRegWin = ImageWindow(ImagePlus("toReg", tmpip)) toRegWin.setLocation(bounds.width + bounds.x, bounds.y) # toRegWin.setVisible(False) toTransformWin = ImageWindow(ImagePlus("toTransform", tmpip)) toTransformWin.setLocation(2 * bounds.width + bounds.x, bounds.y) # toTransformWin.setVisible(False) # get reference image refImp = ImagePlus("ref", stack.getProcessor(imp.getStackIndex(refC, refZ, refT))) refWin.setImage(refImp) tr = TurboReg_() for t in xrange(1, nFrames + 1): IJ.showProgress(t - 1, nFrames) # print "t ", t # do TurboReg on reference channel toRegId = imp.getStackIndex(refC, refZ, t) toRegImp = ImagePlus("toReg", stack.getProcessor(toRegId)) toRegWin.setImage(toRegImp) regArg = "-align " +\ "-window " + toRegImp.getTitle() + " " +\ "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\ "-window " + refImp.getTitle() + " " +\ "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\ "-rigidBody " +\ str(width / 2) + " " + str(height / 2) + " " +\ str(width / 2) + " " + str(height / 2) + " " +\ "0 " + str(height / 2) + " " +\ "0 " + str(height / 2) + " " +\ str(width - 1) + " " + str(height / 2) + " " +\ str(width - 1) + " " + str(height / 2) + " " +\ "-hideOutput" tr = TurboReg_() tr.run(regArg) registeredImp = tr.getTransformedImage() sourcePoints = tr.getSourcePoints() targetPoints = tr.getTargetPoints() registeredStack.setProcessor(registeredImp.getProcessor(), toRegId) # toRegImp.flush() # apply transformation on other channels for c in xrange(1, nChannels + 1): # print "c ", c if c == refC: continue toTransformId = imp.getStackIndex(c, 1, t) toTransformImp = ImagePlus("toTransform", stack.getProcessor(toTransformId)) toTransformWin.setImage(toTransformImp) transformArg = "-transform " +\ "-window " + toTransformImp.getTitle() + " " +\ str(width) + " " + str(height) + " " +\ "-rigidBody " +\ str(sourcePoints[0][0]) + " " +\ str(sourcePoints[0][1]) + " " +\ str(targetPoints[0][0]) + " " +\ str(targetPoints[0][1]) + " " +\ str(sourcePoints[1][0]) + " " +\ str(sourcePoints[1][1]) + " " +\ str(targetPoints[1][0]) + " " +\ str(targetPoints[1][1]) + " " +\ str(sourcePoints[2][0]) + " " +\ str(sourcePoints[2][1]) + " " +\ str(targetPoints[2][0]) + " " +\ str(targetPoints[2][1]) + " " +\ "-hideOutput" tr = TurboReg_() tr.run(transformArg) registeredStack.setProcessor( tr.getTransformedImage().getProcessor(), toTransformId) # toTransformImp.flush() sourcePoints = None targetPoints = None IJ.showProgress(t, nFrames) IJ.showStatus("Frames registered: " + str(t) + "/" + str(nFrames)) refWin.close() toRegWin.close() toTransformWin.close() imp2 = ImagePlus("reg_" + imp.getTitle(), registeredStack) imp2.setCalibration(imp.getCalibration().copy()) imp2.setDimensions(nChannels, nSlices, nFrames) # print "type ", imp.getType() # print "type ", imp2.getType() # print nChannels, " ", nSlices, " ", nFrames # print registeredStack.getSize() for key in imp.getProperties().stringPropertyNames(): imp2.setProperty(key, imp.getProperty(key)) # comp = CompositeImage(imp2, CompositeImage.COLOR) # comp.show() # imp2 = imp.clone() # imp2.setStack(registeredStack) # imp2.setTitle("reg"+imp.getTitle()) # imp2.show() # imp.show() return imp2