def ReturnColorThresholdedPicture(PICPATH, L_min, L_max, a_min, a_max, b_min, b_max): imp = IJ.openImage(PICPATH) imp.show() ImageTitle = imp.getTitle() LabThresold_List = [[L_min, L_max], [a_min, a_max], [b_min, b_max]] Filt_List = ["pass", "pass", "pass"] ColorThresholder.RGBtoLab() IJ.run(imp, "RGB Stack", "") IJ.run("Stack to Images", "") IJ.selectWindow("Red") IJ.run('Rename...', 'title=0') #title=hoge =(equal)の間にスペースを入れてならない。 imp0 = IJ.getImage() IJ.selectWindow("Green") IJ.run('Rename...', 'title=1') imp1 = IJ.getImage() IJ.selectWindow("Blue") IJ.run('Rename...', 'title=2') imp2 = IJ.getImage() for i in range(3): WindowTitle = str(i) MinValue = float(LabThresold_List[i][0]) MaxValue = float(LabThresold_List[i][1]) IJ.selectWindow(WindowTitle) IJ.setThreshold(MinValue, MaxValue) IJ.run(IJ.getImage(), "Convert to Mask", "") if Filt_List[i] == "stop": ImageProcessor.invert() #コメントアウトした、imgculcは動かなくなくなった,謎 #imp3 = ImageCalculator.run(imp0, imp1, "and create") #imp4 = ImageCalculator.run(imp3,imp2, "and create") imp3 = ImageCalculator().run("and create", imp0, imp1) imp4 = ImageCalculator().run("and create", imp3, imp2) imp3.show() imp4.show() ResultTitle = imp4.getTitle() IJ.selectWindow(ResultTitle) imp4.setTitle(ImageTitle) #Saveした時点で画像の情報が失われる. imp.close() imp0.close() imp1.close() imp2.close() imp3.close() return imp4
def run_script(): '''Function to be run when this file is used as a script''' selected_mode, img1_in, img2_in = get_setup() if not selected_mode: return corrected_stack = drift.get_corrected_stack((img1_in, img2_in), mode=selected_mode) img1, img2 = tools.stack_to_list_of_imp(corrected_stack) img_ratio = ImageCalculator().run('Divide create', img2, img1) img_ratio.setTitle('Jump-ratio [%s divided by %s]' % (img2.getShortTitle(), img1.getShortTitle()) ) img_ratio.changes = True img_ratio.copyScale(img1_in) img_ratio.show() IJ.run(img_ratio, 'Enhance Contrast', 'saturated=0.35') # We want to optimise the lower displaylimit: minimum = img_ratio.getProcessor().getMin() maximum = img_ratio.getProcessor().getMax() stat = img_ratio.getStatistics(Stats.MEAN + Stats.STD_DEV) mean = stat.mean stdv = stat.stdDev if minimum < mean - stdv: if mean - stdv >= 0: img_ratio.getProcessor().setMinAndMax(mean - stdv, maximum) else: img_ratio.getProcessor().setMinAndMax(0, maximum) img_ratio.updateAndDraw()
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 process_caspase_signal(path_signal, path_imp, path_imp_out): path_imp = path_signal + path_imp imp = IJ.openImage(path_imp) imp.show() zp = ZProjector(imp) zp.setMethod(ZProjector.AVG_METHOD) zp.doProjection() zpimp = zp.getProjection() imp_sub = ImageCalculator().run("Subtract create stack", imp, zpimp) imp_sub.show() IJ.saveAs(imp_sub, "Tiff", path_signal + path_imp_out) imp.changes = False imp.close() imp_sub.changes = False imp_sub.close()
def process_pi_signal(path, position, unsynchronized=True): if unsynchronized: path_signal = path + "\\pi" path_signal_before = path_signal + "\\before" path_signal_after = path_signal + "\\after" path_signal_merged = path_signal + "\\merged" path_imp_before = path_signal_before + "\\pi_in-focusxy%sc1.tif" % position path_imp_after = path_signal_after + "\\pixy%sc1.tif" % position path_imp_merged = path_signal_merged + "\\merged.tif" path_imp_merged_sub = path_signal_merged + "\\merged_sub.tif" imp1 = IJ.openImage(path_imp_before) imp1.show() imp2 = IJ.openImage(path_imp_after) imp2.show() zp1 = ZProjector(imp1) zp1.setMethod(ZProjector.AVG_METHOD) zp1.doProjection() zpimp1 = zp1.getProjection() zp2 = ZProjector(imp2) zp2.setMethod(ZProjector.AVG_METHOD) zp2.doProjection() zpimp2 = zp2.getProjection() imp_sub1 = ImageCalculator().run("Subtract create stack", imp1, zpimp1) imp_sub1.show() imp_sub2 = ImageCalculator().run("Subtract create stack", imp2, zpimp2) imp_sub2.show() concatenate_files(imp1, imp2, path_imp_merged) concatenate_files(imp_sub1, imp_sub2, path_imp_merged_sub) else: path_signal = path + "\\pi\\seq0002xy%sc1.tif" % position path_sub = path + "\\pi\\sub.tif" imp = IJ.openImage(path_signal) imp.show() zp = ZProjector(imp) zp.setMethod(ZProjector.AVG_METHOD) zp.doProjection() zpimp = zp.getProjection() imp_sub = ImageCalculator().run("Subtract create stack", imp, zpimp) imp_sub.show() IJ.saveAs(imp_sub, "Tiff", path_sub) imp.changes = False imp.close() zpimp.changes = False zpimp.close() imp_sub.changes = False imp_sub.close()
def startTracking(filepath, fdir, ffile, filename): outpath = fdir troutpath = fdir + separator + ffile + separator + "tracked" + separator stackoutpath = fdir + separator + ffile + separator + "stacks" + separator pixwidth = 0.647 interval_sec = 600 #pr if "141006" in fdir: interval_sec = 600 elif "141117" in fdir: interval_sec = 300 elif "141215" in fdir: interval_sec = 300 if not os.path.isdir(outpath): os.mkdir(outpath) if not os.path.isdir(troutpath): os.mkdir(troutpath) if not os.path.isdir(stackoutpath): os.mkdir(stackoutpath) print 'filepath: ', filepath #pr print 'fdir: ', fdir #pr print 'ffile: ', ffile #pr IJ.run("Image Sequence...", "open=" + filepath + " file=" + filename + " sort") #pr #IJ.run("Image Sequence...", "open=" + filepath + " file=molm sort"); #pr imp = WindowManager.getCurrentImage() imptitle = imp.getTitle() nframes = imp.getNSlices() IJ.run( imp, "Properties...", "channels=1 slices=1 frames=" + str(nframes) + " unit=inch pixel_width=" + str(pixwidth) + " pixel_height=" + str(pixwidth) + " voxel_depth=1.0000 frame=[" + str(interval_sec) + " sec]") IJ.run(imp, "Duplicate...", "title=" + imptitle + "_dup duplicate") imp_dup = WindowManager.getImage(imptitle + "_dup") IJ.run(imp_dup, "Gaussian Blur...", "sigma=50 stack") ic = ImageCalculator() imp_corr = ic.run("Divide create 32-bit stack", imp, imp_dup) imp_corr.setTitle(imptitle + "_corrected") imp_corr.show() imp.changes = False imp.close() imp_dup.changes = False imp_dup.close() IJ.run(imp_corr, "8-bit", "") IJ.run( imp_corr, "Normalize Local Contrast", "block_radius_x=100 block_radius_y=100 standard_deviations=1 stretch stack" ) IJ.saveAs(imp_corr, "Tiff", stackoutpath + separator + imptitle + "_corrected.tif") IJ.run(imp_corr, "Duplicate...", "title=" + imptitle + "_bg duplicate") imp_bg = WindowManager.getImage(imptitle + "_bg") #Prefs.blackBackground = True; IJ.setAutoThreshold(imp_bg, "MinError dark") IJ.run(imp_bg, "Convert to Mask", "stack") IJ.run(imp_bg, "Analyze Particles...", "size=10000-Infinity show=Masks stack") imp_bg.changes = False imp_bg.close() imp_bgmask = WindowManager.getImage("Mask of " + imptitle + "_bg") ic = ImageCalculator() imp_corr_wobg = ic.run("Subtract create stack", imp_corr, imp_bgmask) imp_corr_wobg.setTitle(imptitle + "_corrected_womask") imp_corr_wobg.show() IJ.saveAs(imp_corr_wobg, "Tiff", stackoutpath + separator + imptitle + "_corrected_womask.tif") #pr # pr: substract average frames zp = ZProjector(imp_corr_wobg) zp.setMethod(ZProjector.AVG_METHOD) zp.doProjection() zpimp = zp.getProjection() zpimp.show() imp_corr_wobg_sub = ImageCalculator().run("Subtract create stack", imp_corr_wobg, zpimp) imp_corr_wobg_sub.show() #imp_corr_wobg.changes = False #imp_corr_wobg.close() # pr: subtract average frames (END) IJ.saveAs( imp_corr_wobg_sub, "Tiff", stackoutpath + separator + imptitle + "_corrected_womask_substracted.tif") #pr IJ.saveAs( zpimp, "Tiff", stackoutpath + separator + imptitle + "_corrected_womask_avg.tif") #commented out: pr #IJ.saveAs(imp_corr_wobg, "Tiff", stackoutpath+separator+imptitle+"_corrected_womask.tif"); IJ.saveAs(imp_bgmask, "Tiff", stackoutpath + separator + imptitle + "_bgmask.tif") print(stackoutpath + separator + imptitle + "_corrected_womask_substracted.tif") print(stackoutpath + separator + imptitle + "_corrected_womask_avg.tif") print(stackoutpath + separator + imptitle + "_bgmask.tif") imp_corr.changes = False imp_corr.close() imp_bgmask.changes = False imp_bgmask.close() imp_corr_wobg.changes = False imp_corr_wobg.close() #imp_corr_wobg_sub.changes = False #imp_corr_wobg_sub.close() zpimp.changes = False zpimp.close() #IJ.log(System.getProperty("os.name")) #IJ.log(fdir) return imp_corr_wobg_sub
from ij.plugin import ChannelSplitter, ImageCalculator # Split color channels red, green, blue = ChannelSplitter().split(imp_rgb) # 3 ImagePlus # Set threshold for each slice for index in xrange(1, red.getNSlices() + 1): bp = red.getStack().getProcessor(index) #bp.setThreshold(threshold, 255, ImageProcessor.BLACK_AND_WHITE_LUT) bp.threshold(threshold) # mask is 0, background is 255 # Apply threshold: convert each slice to a mask (only 0 or 255 pixel values) #IJ.run(red, "Convert to Mask", "method=Default background=Dark black") red.show() green_under_red_mask = ImageCalculator().run("and create stack", red, green) green_under_red_mask.show() """ # Example 2: with ImgLib2 LoopBuilder from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.converter import Converters from net.imglib2.img.array import ArrayImgs from net.imglib2.util import Intervals from net.imglib2.loops import LoopBuilder img = IL.wrap(imp_rgb) # an ARGBType Img red = Converters.argbChannel(img, 1) # a view of the ARGB red channel green = Converters.argbChannel(img, 2) # a view of the ARGB green channel img_sub = ArrayImgs.unsignedBytes(Intervals.dimensionsAsLongArray(img)) # the img to store the result class Consumer(LoopBuilder.TriConsumer):
"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]") impd = IJ.getImage() impd.setTitle("albedo") #calculating normals N = ImageCalculator().run("Divide create 32-bit stack", impc, impd) N.show() #IJ.run("Rotate 90 Degrees Right") #IJ.run("Flip Horizontally", "stack") impf = IJ.getImage() impf.setTitle("32 bit Surface Normal Map") #converting to 8 bit color image IJ.run("Duplicate...", "duplicate") IJ.run("8-bit") impe = IJ.getImage() impe.changes = False IJ.run("Stack to RGB") impg = IJ.getImage() impg.setTitle("8 bit Surface Normal Map") impc.close()
except: pass rm.reset() for proc in (nucMaskStack2.getProcessor(n) for n in range(1, nucMaskStack2.size() + 1)): proc.threshold(1) nucMaskIp2 = ImagePlus("Masked Nuclei", nucMaskIp.getStack().getProcessor(1)) nucMaskIp2.setStack(nucMaskStack2) #This calculates the voronoi diagram IJ.run(nucMaskIp2, "8-bit", "") nucMaskStack2 = nucMaskIp2.getStack() IJ.run(nucMaskIp2, "Close", "stack") IJ.run(nucMaskIp2, "Invert", "stack") IJ.run(nucMaskIp2, "Voronoi", "stack") for proc in (nucMaskStack2.getProcessor(n) for n in range(1, nucMaskStack2.size() + 1)): proc.threshold(0) IJ.run(nucMaskIp2, "Invert", "stack") #This burns the boundary lines of the voronoi diagram into the nuclear mask image, completing the segmentation nucAnalyzeIp = ImageCalculator().run("AND create stack", nucMaskIp, nucMaskIp2) nucAnalyzeIp.show() #This measures the nuclei IJ.run("Set Measurements...", "area mean centroid fit shape feret's stack decimal=3") Analyzer.setRedirectImage(nucIpForMeasure) IJ.run(nucAnalyzeIp, "Analyze Particles...", "display stack") rt = ResultsTable.getResultsTable() groupString = '_'.join("%s=%s" % (key,''.join(val)) for (key,val) in zip(groupBy, outerPairs)) rt.saveAs(outputFolder +r"/nuclei_" + groupString + ".csv") IJ.run("Clear Results") rt = ResultsTable.getResultsTable() #This links nuclei to their respective cardiomyocyte (if present). The cardiomyocyte count mask image #has each pixel within a given cardiomyocyte set to its id number, so the minimum value for a nucleus roi in the cardiomyocyte #count mask image will be that cardiomyocyte's id number if the nucleus is 100% contained within a cardiomyocyte #or zero if not Analyzer.setRedirectImage(cmIp) IJ.run("Set Measurements...", "min decimal=3")
IJ.run(imp, "Duplicate...", "title=wy") #create wy by rotating wx by 90 degrees IJ.run("Rotate 90 Degrees Left") imp2 = IJ.getImage() imp2.changes = False #integration in the phase domain by shifting Pi/2, see equation 21 in Frankot-Chellapa A = ImageCalculator().run("Multiply create 32-bit stack", DZDX, imp) B = ImageCalculator().run("Multiply create 32-bit stack", DZDY, imp2) # numerator of C = ImageCalculator().run("Add create 32-bit stack", A, B) # eq 21 D = ImageCalculator().run("Multiply create 32-bit", imp, imp) # square wx E = ImageCalculator().run("Multiply create 32-bit", imp2, imp2) # square wy F = ImageCalculator().run("Add create 32-bit", D, E) # demnominator of eq 21 Z = ImageCalculator().run("Divide create 32-bit stack", C, F) # solve eq 21 Z.show() IJ.run("Inverse FFT") #results of integration IJ.run( "Stack to Images" ) #separate real and imaginary... why does imaginary produce result? more reading needed. #clean-up by closing un-necessary images imp2.close() DZDX.close() DZDY.close() imp.changes = False imp.close() A.changes = False A.close() Z.close()
def BackgroundFilter(): def setupDialog(imp): gd = GenericDialog("Toolbox options") gd.addMessage("Imagej toolbox, you are analyzing: " + imp.getTitle()) calibration = imp.getCalibration() if (calibration.frameInterval > 0): default_interval = calibration.frameInterval default_timeunit = calibration.getTimeUnit() else: default_interval = 10 default_timeunit = "sec" gd.addNumericField("Frame interval:", default_interval, 2) # show 2 decimals # gd.addCheckbox("Do you want to use a gliding window?", True) # gd.addCheckbox("Project hyperStack? (defaluts to projecting current channel only)", False) # gd.addStringField("time unit",default_timeunit, 3) # gd.addSlider("Start compacting at frame:", 1, imp.getNFrames(), 1) # gd.addSlider("Stop compacting at frame:", 1, imp.getNFrames(), imp.getNFrames()) # gd.addNumericField("Number of frames to project in to one:", 3, 0) # show 0 decimals gd.addChoice('Method to use for stack background filtering:', methods_as_strings, methods_as_strings[5]) gd.showDialog() if gd.wasCanceled(): IJ.log("User canceled dialog!") return return gd #Start by getting the active image window and get the current active channel and other stats imp = WindowManager.getCurrentImage() cal = imp.getCalibration() nSlices = 1 #TODO fix this in case you want to do Z-stacks title = imp.getTitle() current_channel = imp.getChannel() #zp = ZProjector(imp) #Make a dict containg method_name:const_fieled_value pairs for the projection methods methods_as_strings = [ 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median' ] methods_as_const = [ ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD, ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD ] method_dict = dict(zip(methods_as_strings, methods_as_const)) gd = setupDialog(imp) #The Z-Projection magic happens here through a ZProjector object zp = ZProjector(imp) projection_method = gd.getNextChoice() chosen_method = method_dict[projection_method] zp.setMethod(chosen_method) outstack = imp.createEmptyStack() zp.doProjection() outstack.addSlice(zp.getProjection().getProcessor()) imp2 = ImagePlus(title + '_' + projection_method, outstack) # imp2.show() imp3 = ImageCalculator().run("Subtract create 32-bit stack", imp, imp2) imp3.show() Startmenu()
height = imp.height num_slices = imp.getNSlices() num_channels = imp.getNChannels() num_frames = imp.getNFrames() max_cycle_length = int(max_cycle_length) assert width_sub < width and width_sub < height, "Size of square must be less than dimensions of movie" assert num_channels == 1, "Image can only have one channel" #imp = process.ImageConverter.convertToGray32(original_imp) avg_img = ZProjector.run(imp,"avg"); avg_img.show() imp2 = ImageCalculator().run("Subtract create stack", imp, avg_img) imp2.show() #WindowManager.getImage("AVG_Pos0") num_window_x = int(round(width/width_sub)) #int(width-width_sub+1) num_window_y = int(round(height/width_sub)) #int(height-width_sub+1) center_px = int(round(width_sub/2)) new_rois = [] for i in range(0,num_window_x): for j in range(0,num_window_y): new_roi = Roi(i*width_sub, j*width_sub, width_sub, width_sub) new_rois.append(new_roi) for new_roi in new_rois: rm.addRoi(new_roi)