def measure_rm(img_path, roi_path): imp = IJ.openImage(img_path) img_dir = imp.getOriginalFileInfo().directory img_file = imp.getOriginalFileInfo().fileName ip = imp.getProcessor() cal = Calibration(imp) rm = RoiManager() rm = RoiManager.getInstance() rm.runCommand("Open", roi_path) roi_array = rm.getRoisAsArray() moptions = Measurements.MEAN | Measurements.AREA for roi in roi_array: roi_name = roi.getName() ip.setRoi(roi) stat = ImageStatistics.getStatistics(ip, moptions, cal) IJ.log(img_dir + "\t" + img_file + "\t" + roi_name + "\t" + str(stat.pixelCount) + "\t" + str(stat.pixelCount * stat.umean) + "\t" + str(stat.umean)) rm.runCommand("delete")
def getMedians(imPlus): medians = [] stk = imPlus.getStack() for i in range(stk.getSize()): img_stats = ImageStatistics.getStatistics(stk.getProcessor(i + 1), Measurements.MEDIAN, Calibration()) medians.append(img_stats.median) print('GOT MEDIANS') return medians
def get_convexfull_area(self, i, imp=IJ.getImage()): convexfull = self.roi_array[i].getFloatConvexHull() convexfull_roi = PolygonRoi(convexfull, Roi.POLYGON) imp.setRoi(convexfull_roi) moptions = Measurements.MEAN | Measurements.INTEGRATED_DENSITY | Measurements.AREA ip = imp.getProcessor() cal = Calibration(imp) stat = ImageStatistics.getStatistics(ip, moptions, cal) convexfull_are = stat.area return convexfull_are
def backgroundSubtraction(imp): """ subtract background, Cihan's method. see Simpson(2007) """ impstats = imp.getProcessor().getStatistics() # backlevel = impstats.min + (impstats.mean - impstats.min)/2 imp.getProcessor().setThreshold(impstats.min, impstats.mean, ImageProcessor.RED_LUT) measOpt = ImageStatistics.MEAN + ImageStatistics.LIMIT impstats = ImageStatistics.getStatistics(imp.getProcessor(), measOpt, None) backlevel = impstats.mean imp.getProcessor().resetThreshold() imp.getProcessor().subtract(backlevel) print imp.getTitle(), " : background intensity - ", backlevel return backlevel
def autoAdjust(ip): """ Find min and max using the equivalent of clicking "Auto" in ImageJ/Fiji's Brightness & Contrast dialog (the method autoAdjust in the ij.plugin.frame.ContrastAdjuster class). ip: an ImageProcessor. Return the min and max (possibly as floating-point values). """ stats = ImageStatistics.getStatistics(ip, ImageStatistics.MIN_MAX, None) limit = stats.pixelCount / 10 f = ImageStatistics.getDeclaredField("histogram") histogram = f.get(stats) # stats.histogram is confused with stats.getHistogram(), with the latter returning a long[] version. threshold = stats.pixelCount / 2500 # autoThreshold / 2 # Search for histogram min i = 0 found = False while not found and i < 255: count = histogram[i] if count > limit: count = 0 found = count > threshold i += 1 hmin = i # Search for histogram max i = 255 found = False while not found and i > 0: count = histogram[i] if count > limit: count = 0 found = count > threshold i -= 1 hmax = i # Convert hmax, hmin to min, max if hmax > hmin: minimum = stats.histMin + hmin * stats.binSize maximum = stats.histMin + hmax * stats.binSize if minimum == maximum: minimum = stats.min maximum = stats.max else: sp.findMinAndMax() minimum = sp.getMin() maximum = sp.getMax() return minimum, maximum
def getDICfocus(imp): stack = imp.getStack() focusStack = ImageStack(W,H) for t in range(1,T+1): sd = [0 for z in range(Z+1)] for z in range(1,Z+1): #get best focussed C2 (DIC) slices ip = stack.getProcessor(imp.getStackIndex(2,z,t)).convertToFloat() ip.findEdges() sd[z] = ImageStatistics.getStatistics(ip, Measurements.STD_DEV, cal).stdDev focusZ = sd.index(max(sd)) focusSlice = stack.getProcessor(imp.getStackIndex(2,focusZ,t)).convertToFloatProcessor() focusStack.addSlice("Z"+str(focusZ), focusSlice) #ImagePlus("DIC focus", focusStack).show() #exit(0) return focusStack
def brightest_pixels(imp): ip = imp.getProcessor().convertToFloat() pixels = ip.getPixels() # type 'array' options = IS.MEAN | IS.MEDIAN | IS.MIN_MAX stats = IS.getStatistics(ip, options, imp.getCalibration()) # Print image details #print "number of slices:", imp.getNSlices() #print "number of channels:", imp.getNChannels() #print "number of time frames:", imp.getNFrames() brightestpixellist = all_indices(stats.max, list(pixels)) #print "pixels with max. value:", brightestpixellist for bp in brightestpixellist: x = bp % imp.width y = bp / imp.width #print "max. brightness coordinates:", x, y # note that this chooses for x, y the last element in the brightestpixelist which is OK if there is only one element # TODO: would be nicer to loop over this list or specify which element to pick return x, y
def locateTumors(imp): '''Locates the tumors in an image; white is location, black is not''' # Determine if the tumor is black on a white background or white # on a black background ip = imp.getProcessor() stats = IS.getStatistics(ip, IS.MEAN, imp.getCalibration()) mean = stats.mean if mean >= 20: # Black tumor on white background IJ.run(imp, 'Subtract Background...', 'rolling=' + str(backgroundRadius) + ' light sliding stack'); IJ.run(imp, "Invert", "stack") else: IJ.run(imp, 'Subtract Background...', 'rolling=' + str(backgroundRadius) + ' sliding stack'); IJ.run(imp, 'Median...', 'radius=' + str(medianSmoothing)) IJ.run(imp, 'Auto Threshold', 'method=MaxEntropy white stack') # Remove small IJ.setForegroundColor(0, 0, 0); IJ.run(imp, 'ParticleRemoverPy ', 'enter=' + str(minimumCancerArea)); IJ.run(imp, "Close-", "stack") # Make sure black background binary is set! IJ.run(imp, "Options...", "iterations=1 count=1 black edm=Overwrite"); IJ.run(imp, 'Fill Holes', "stack") IJ.run(imp, 'Watershed', "stack") IJ.run(imp, 'ParticleRemoverPy ', 'enter=' + str(minimumCancerArea));
def normalizeContrast(imp): # The width and height of the box centered at every pixel: blockRadiusX = 100 # in pixels blockRadiusY = 100 # The number of standard deviations to expand to stds = 2 # Whether to expand from the median value of the box or the pixel's value center = True # Whether to stretch the expanded values to the pixel depth of the image # e.g. between 0 and 255 for 8-bit images, or e.g. between 0 and 65536, etc. stretch = True # Duplicate the ImageProcessor copy_ip = imp.getProcessor().duplicate() # Apply contrast normalization to the copy NormalizeLocalContrast().run(copy_ip, 200, 200, stds, center, stretch) # Return as new image # Threshold image by mean options = IS.MEAN stats = IS.getStatistics(copy_ip, options, imp.getCalibration()) copy_ip.subtract(int(stats.mean) / 2) return ImagePlus(imp.getTitle(), copy_ip)
output_dc = DirectoryChooser("Choose output folder.") outputDir = output_dc.getDirectory() # What we need to do is crop EQUAL AREAS. First find the smallest # image area. # Find the minimum area per pixel minArea = 999999 for filename in os.listdir(inputDir): if '.tif' in filename: print 'Opening ' , filename , '...' image = IJ.openImage(inputDir + '/' + filename) ip = image.getProcessor() stats = IS.getStatistics(ip, IS.AREA, image.getCalibration()) currentArea = stats.area if currentArea < minArea: minArea = currentArea # Cut smaller than the minArea so that your cut does not run into # any barriers minArea = minArea/4 # Now loop and crop the images for filename in os.listdir(inputDir): if '.tif' in filename: print 'Cropping ' , filename , '...' image = IJ.openImage(inputDir + '/' + filename) # Get the calibration
signalRoi.setPosition(c+1) colour = Color.BLUE if c==1: colour = Color.CYAN elif c==2: colour = Color.GREEN elif c==3: colour = Color.RED signalRoi.setStrokeColor(colour) ol.add(signalRoi) ip = [imp.getStack().getProcessor(c+1) for c in range(0, C)] points = [] row = 0 npos = [0 for i in range(C)] pos13 = 0 pos12 = 0 for roi in rois: ip[0].setRoi(roi) area = ImageStatistics.getStatistics(ip[0], Measurements.AREA, cal).area if area>=MINA and area<=MAXA: roi.setStrokeColor(Color.YELLOW) bounds = roi.getBounds() rt.setValue("X", row, (bounds.x+bounds.width/2)*cal.pixelWidth) rt.setValue("Y", row, (bounds.y+bounds.height/2)*cal.pixelHeight) rt.setValue("Area", row, area) stats = [i for i in range(0,C)] call = [False for i in range(C)] for c in range(1, C): ip[c].setRoi(roi) stats[c] = ImageStatistics.getStatistics(ip[c], Measurements.MEAN, cal) rt.setValue("C"+str(c+1)+" "+channels[c]+" Mean", row, stats[c].mean) masks[c].setRoi(roi)
########################################################################################## # 5) Collecting intensities over time ########################################################################################## If = [] # Definition of array that will contain intensities of FRAP ROI Ir = [] # Definition of array that will contain intensities of REF ROI Ib = [] # Definition of array that will contain intensities of BACK ROI # Loop over each slice of the stack for i in range(0, n_slices): # Get the current slice ip = stack.getProcessor(i + 1) # FRAP intensities ip.setRoi(MyRoi) #Define ROI stats = ImageStatistics.getStatistics(ip, Measurements.MEAN, calibration) #Calculate mean If.append(stats.mean) #Store calculated mean in If # non-FRAPed area (ref) ip.setRoi(roi_REF) stats = ImageStatistics.getStatistics(ip, Measurements.MEAN, calibration) Ir.append(stats.mean) # Do the same for background ip.setRoi(roi_BACK) stats = ImageStatistics.getStatistics(ip, Measurements.MEAN, calibration) Ib.append(stats.mean) ########################################################################################## # 6) Create .txt file with results (format FRAP Analyzer)
import os from os import path imp = IJ.getImage() fs = FileSaver(imp) # Print image details print "width:", imp.width print "height:", imp.height print "number of pixels:", imp.width * imp.height # Get its ImageProcessor ip = imp.getProcessor() options = IS.MEAN | IS.MEDIAN | IS.MIN_MAX stats = IS.getStatistics(ip, options, imp.getCalibration()) # print statistics on the image print "Mean:", stats.mean print "Median:", stats.median print "Min and max:", stats.min, "-", stats.max # Grab currently active image imp = IJ.getImage() ip = imp.getProcessor().convertToFloat() pixels = ip.getPixels() # Compute the mean value (sum of all divided by number of pixels) #mean = reduce(lambda a, b: a + b, pixels) / len(pixels) # Get a list of pixels above the mean
rm = RoiManager.getInstance() roi_list = rm.getRoisAsArray() # ビット論理和を取ることで設定したい値を変えられる moptions = Measurements.MEAN | Measurements.AREA IJ.log("\\Clear") IJ.log("Directory" + "\t" + "File" + "\t" + "Roi_id" + "\t" + "Object" + "\t" + "Area" + "\t" + "Integrated_density" + "\t" + "Mean_intensity") for roi in roi_list: roi_name = roi.getName() roi_name_sp = roi_name.split("_") if len(roi_name_sp) >= 2: roi_id = roi_name_sp[0] obj = roi_name_sp[1] else: roi_id = roi_name_sp[0] obj = "None" ip.setRoi(roi) stat = ImageStatistics.getStatistics(ip, moptions, cal) # Measurementの値を指定するにはmoptionでMeasuremnt Classのbit論理和を取る IJ.log(img_dir + "\t" + img_file + "\t" + roi_id + "\t" + obj + "\t" + str(stat.pixelCount) + "\t" + str(stat.pixelCount * stat.umean) + "\t" + str(stat.umean))
def getMean(ip, imp): """ Return mean for the given ImagePlus and ImageProcessor """ global options stats = IS.getStatistics(ip, options, imp.getCalibration()) return stats.mean
def segmentation(imp, spot_data, channel, diameter_init, ES_tolerance, ES_area_max, ES_ctrl_pts, ES_iteration, repeat_max): # Open files cal = imp.getCalibration() manager = RoiManager.getInstance() if manager is None: manager = RoiManager() # Prepare log files for output options = IS.MEDIAN | IS.AREA | IS.MIN_MAX | IS.CENTROID | IS.PERIMETER | IS.ELLIPSE | IS.SKEWNESS convergence = [] Sintensity = [] for spot in spot_data: repeat = 0 flag = False spotID = int(spot[0]) Xcenter = (float(spot[1]) / cal.pixelWidth) Ycenter = (float(spot[2]) / cal.pixelHeight) Quality = float(spot[3]) diameter_init = float(spot[4] / cal.pixelWidth) * 2.0 while True: manager = RoiManager.getInstance() if manager is None: manager = RoiManager() Xcurrent = int(Xcenter - diameter_init / 2.0) Ycurrent = int(Ycenter - diameter_init / 2.0) Dcurrent1 = int(diameter_init * (1.2 - repeat / 10.0)) Dcurrent2 = int(diameter_init * (0.8 + repeat / 10.0)) roi = OvalRoi(Xcurrent, Ycurrent, Dcurrent1, Dcurrent2) imp.setPosition(channel) imp.setRoi(roi) Esnake_options1 = "target_brightness=Bright control_points=" + \ str(ES_ctrl_pts) + " gaussian_blur=0 " Esnake_options2 = "energy_type=Contour alpha=2.0E-5 max_iterations=" + \ str(ES_iteration) + " immortal=false" IJ.run(imp, "E-Snake", Esnake_options1 + Esnake_options2) roi_snake = manager.getRoisAsArray() roi_ind = len(roi_snake) - 1 stats = IS.getStatistics( imp.getProcessor(), options, imp.getCalibration()) perimeter = roi_snake[roi_ind].getLength() * cal.pixelWidth circularity = 4.0 * 3.1417 * (stats.area / (perimeter * perimeter)) if stats.area > 17.0 and stats.area < ES_area_max and stats.skewness < -0.01 and circularity > 0.01 and stats.minor > 2.0 and boundaries(Xcenter, Ycenter, stats.xCentroid / cal.pixelWidth, stats.yCentroid / cal.pixelHeight, ES_tolerance): Sintensity = stats.median convergence.append(True) break if stats.median > 6000 and stats.area > 17.0 and stats.area < ES_area_max: Sintensity = stats.median convergence.append(True) break elif repeat > repeat_max: manager.select(imp, roi_ind) manager.runCommand(imp, 'Delete') roi = OvalRoi(Xcenter + 1.0 - diameter_init / 2.0, Ycenter + 1.0 - diameter_init / 2.0, diameter_init, diameter_init) imp.setRoi(roi) manager.add(imp, roi, spotID) roi_snake.append(roi) stats = IS.getStatistics( imp.getProcessor(), options, imp.getCalibration()) Sintensity = stats.median convergence.append(False) break else: IJ.log('Area=' + str(stats.area) + ' Skewness=' + str(stats.skewness) + ' circularity=' + str(circularity) + ' Minor=' + str(stats.minor)) manager.select(imp, roi_ind) manager.runCommand(imp, 'Delete') repeat += 1 # End Spot-segmentation # End all Spots-segmentation manager.runCommand(imp, 'Show All') imp.setPosition(channel) color = imp.createImagePlus() ip = imp.getProcessor().duplicate() color.setProcessor("segmentation" + str(channel), ip) color.show() IJ.selectWindow("segmentation" + str(channel)) manager.moveRoisToOverlay(color) spot_optimal = manager.getRoisAsArray() manager.reset() for i in xrange(0, len(spot_optimal)): spot = spot_optimal[i] spot.setStrokeWidth(2) if convergence[i]: spot.setStrokeColor(Color.GREEN) else: spot.setStrokeColor(Color.MAGENTA) imp.setRoi(spot) manager.add(imp, spot, i) manager.runCommand(imp, 'Show All') imp.setPosition(channel)
# use centre of mass to locate film, use http://imagej.net/developer/api/ij/process/ImageStatistics.html from ij import IJ from ij.process import ImageStatistics as IS from ij.process import ImageProcessor from ij.measure import Measurements as Measure imp = IJ.openImage("C:\\Users\\RCole02\\Desktop\\images\\wrong.JPG") imp.show() if imp.height > imp.width: IJ.run(imp, "Rotate 90 Degrees Right", "") print "image now horizontal" ip = imp.getProcessor() stats = IS.getStatistics(ip, Measure.CENTER_OF_MASS, imp.getCalibration()) print "xCenterOfMass: " + str(stats.xCenterOfMass) + "yCenterOfMass: " + str( stats.yCenterOfMass) if stats.yCenterOfMass < 0.5 * imp.height: IJ.run(imp, "Flip Vertically", "")
def getStatistics(imp): """ Return statistics for the given ImagePlus """ options = IS.MEAN | IS.MEDIAN | IS.MIN_MAX |IS.STD_DEV|IS.KURTOSIS|IS.SKEWNESS ip = imp.getProcessor() stats = IS.getStatistics(ip, options, imp.getCalibration()) return stats.mean, stats.median, stats.min, stats.max, stats.stdDev,stats.kurtosis,stats.skewness
def getStatistics(imp): """ Return statistics for the given ImagePlus """ options = IS.MEAN | IS.MEDIAN | IS.MIN_MAX ip = imp.getProcessor() stats = IS.getStatistics(ip, options, imp.getCalibration()) return stats.mean, stats.median, stats.min, stats.max
def channel_segmentation(infile, diameter, tolerance, repeat_max, Zrepeat=10): # ROI optimization by Esnake optimisation default_options = "stack_order=XYCZT color_mode=Grayscale view=Hyperstack" IJ.run("Bio-Formats Importer", default_options + " open=[" + infile + "]") imp = IJ.getImage() cal = imp.getCalibration() channels = [i for i in xrange(1, imp.getNChannels() + 1)] log = filename(infile) log = re.sub('.ids', '.csv', log) XZdrift, YZdrift = retrieve_Zdrift(log) XZpt = [i * imp.getWidth() / Zrepeat for i in xrange(1, Zrepeat - 1)] YZpt = [i * imp.getHeight() / Zrepeat for i in xrange(1, Zrepeat - 1)] # Prepare head output file for ch in channels: csv_name = 'ch' + str(ch) + log with open(os.path.join(folder6, csv_name), 'wb') as outfile: SegLog = csv.writer(outfile, delimiter=',') SegLog.writerow(['spotID', 'Xpos', 'Ypos', 'Zpos', 'Quality', 'area', 'intensity', 'min', 'max', 'std']) # Retrieve seeds from SpotDetector options = IS.MEDIAN | IS.AREA | IS.MIN_MAX | IS.CENTROID spots = retrieve_seeds(log) for ch in channels: for spot in spots: repeat = 0 # Spots positions are given according to calibration, need to # convert it to pixel coordinates spotID = int(spot[0]) Xcenter = int(float(spot[2]) / cal.pixelWidth) Ycenter = int(float(spot[3]) / cal.pixelHeight) Zcenter = float(spot[4]) / cal.pixelDepth Quality = float(spot[5]) # find closest grid location in Zdrift matrix Xpt = min(range(len(XZpt)), key=lambda i: abs(XZpt[i] - Xcenter)) Ypt = min(range(len(YZpt)), key=lambda i: abs(YZpt[i] - Ycenter)) # Calculate Z position according to SpotZ, calibration and # channel-specific Zdrift # Zshift = median([float(XZdrift[Xpt][ch - 1]), float(YZdrift[Ypt][ch - 1])]) / cal.pixelDepth correctZ = int(Zcenter - Zshift) imp.setPosition(ch, correctZ, 1) imp.getProcessor().setMinAndMax(0, 3000) while True: manager = RoiManager.getInstance() if manager is None: manager = RoiManager() roi = OvalRoi(Xcenter - diameter * (1.0 + repeat / 10.0) / 2.0, Ycenter - diameter * ( 1.0 + repeat / 10.0) / 2.0, diameter * (1.0 + repeat / 10.0), diameter * (1.0 + repeat / 10.0)) imp.setRoi(roi) IJ.run(imp, "E-Snake", "target_brightness=Bright control_points=3 gaussian_blur=0 energy_type=Mixture alpha=2.0E-5 max_iterations=20 immortal=false") roi_snake = manager.getRoisAsArray()[0] imp.setRoi(roi_snake) stats = IS.getStatistics( imp.getProcessor(), options, imp.getCalibration()) manager.reset() if stats.area > 20.0 and stats.area < 150.0 and boundaries(Xcenter, Ycenter, stats.xCentroid / cal.pixelWidth, stats.yCentroid / cal.pixelHeight, tolerance): Sarea = stats.area Sintensity = stats.median Smin = stats.min Smax = stats.max Sstd = stats.stdDev break elif repeat > repeat_max: roi = OvalRoi(Xcenter - diameter / 2.0, Ycenter - diameter / 2.0, diameter, diameter) imp.setRoi(roi) manager.add(imp, roi, i) stats = IS.getStatistics( imp.getProcessor(), options, imp.getCalibration()) Sarea = stats.area Sintensity = stats.median Smin = stats.min Smax = stats.max Sstd = stats.stdDev break else: repeat += 1 # Save results csv_name = 'ch' + str(ch) + log with open(os.path.join(folder6, csv_name), 'ab') as outfile: SegLog = csv.writer(outfile, delimiter=',') SegLog.writerow([spotID, Xcenter, Ycenter, correctZ, Quality, Sarea, Sintensity, Smin, Smax, Sstd]) # End spot optimization # End spots # End channels IJ.selectWindow(filename(infile)) IJ.run("Close")
#MEASUREMENT #XYpositions is inverted (like the plot) and shift in z position xyoffset = math.floor(thdist/2) options = IS.INTEGRATED_DENSITY | IS.AREA | IS.MEAN | IS.STD_DEV cal = Calibration() rt = ResultsTable() ct = 0 for i in range(len(xA)): if neighbornumA[i] == 0: ipch2 = impch2.getImageStack().getProcessor(int(zA[i]) + 1) ipch3 = impch3.getImageStack().getProcessor(int(zA[i]) + 1) dotRoi = OvalRoi(int(yA[i] - xyoffset), int(xA[i] - xyoffset), thdist, thdist) ipch2.setRoi(dotRoi) #stats = IS.getStatistics(ip, options, imp.getCalibration()) stats = IS.getStatistics(ipch2, options, cal) ipch3.setRoi(dotRoi) statsch3 = IS.getStatistics(ipch3, options, cal) print "dot", i print "...ch2 TotalInt ", stats.area * stats.mean print "...ch2 Area ", stats.area print "...ch2 mean ", stats.mean print ".." print "...ch3 TotalInt ", statsch3.area * statsch3.mean print "...ch3 Area ", statsch3.area print "...ch3 mean ", statsch3.mean rt.incrementCounter() rt.setValue("DotID", ct, i) rt.setValue("DotX", ct, yA[i]) rt.setValue("DotY", ct, xA[i]) rt.setValue("DotZ", ct, zA[i])
def getStatistics(imp): """ Return statistics for the given ImagePlus """ global options ip = imp.getProcessor() stats = IS.getStatistics(ip, options, imp.getCalibration()) return stats.mean, stats.median, stats.min, stats.max, stats.area
def getStatistics(imp): """ Return statistics for the given ImagePlus """ global options ip = imp.getProcessor() stats = IS.getStatistics(ip, options, imp.getCalibration()) return stats.mean, stats.median, stats.min, stats.max
def run(): ### Default arguments two_sarcomere_size = 25 # determined by filter used. rotation_angle = 0.0 ### Get the image we'd like to work with. # Don't need to ask where to save the intermediate image since it'll just be saved in the matchedmyo folder anyway # may change this though. In case they want to keep that image around. this_img = WindowManager.getCurrentImage() if this_img == None: ud = WaitForUserDialog( "Please select the image you would like to analyze.") ud.show() this_img = WindowManager.getCurrentImage() img_name = this_img.getTitle() matchedmyo_path = "/home/AD/dfco222/scratchMarx/matchedmyo/" # this would be grabbed from the prompt gd = GenericDialog("Preprocessing Options") gd.addCheckbox("Automatic Resizing/Rotation", True) gd.addCheckbox("CLAHE", True) gd.addCheckbox("Normalization to Transverse Tubules", True) gd.showDialog() if gd.wasCanceled(): return auto_resize_rotate = gd.getNextBoolean() clahe = gd.getNextBoolean() normalize = gd.getNextBoolean() if auto_resize_rotate: # Clear selection so it takes FFT of full image rotation_angle = auto_resize_angle_measure(this_img, two_sarcomere_size) if clahe: clahe_args = "blocksize={} histogram=256 maximum=3 mask=*None* fast_(less_accurate)".format( two_sarcomere_size) IJ.run(this_img, "Enhance Local Contrast (CLAHE)", clahe_args) if normalize: # Ask the user to select a subsection of the image that looks healthy-ish. ud = WaitForUserDialog( "Please select a subsection exhibiting a measure of healthy TT structure using the Rectangle tool.\n" + " Only a single cell or several are needed.\n\n" + " Press 'OK' when finished.") ud.show() IJ.setTool("rectangle") # Duplicate the selected subsection. selection = this_img.crop() IJ.run(selection, "Duplicate...", "title=subsection.tif") # Grab the subsection image and rotate it. selection = WindowManager.getImage("subsection.tif") IJ.run( selection, "Rotate...", "angle={} grid=1 interpolation=Bicubic enlarge".format( rotation_angle)) # Ask the user to select a bounding box that contains only tubules # NOTE: Need to get rid of initial selection since it's the entire image and it's annoying to click out of IJ.setTool("rectangle") IJ.run(selection, "Select None", "") ud = WaitForUserDialog( "Select a subsection of the image that contains only tubules and no membrane." ) ud.show() # Grab the subsection ImagePlus selection = WindowManager.getCurrentImage() this_window = WindowManager.getActiveWindow() selection_small = selection.crop() IJ.run(selection, "Close", "") # NOTE: May not actually display this depending on how the macros work IJ.run(selection_small, "Duplicate...", "title=subsection_small.tif") # Smooth the selection using the single TT filter. # NOTE: It won't read in so we're just going to hard code it in since it's simple tt_filt_row = "0 0 0 1 1 1 1 1 1 0 0 0 0\n" tt_filt = "" for i in range(21): tt_filt += tt_filt_row IJ.run("Convolve...", "text1=[" + tt_filt + "] normalize") # Segment out the TTs from the 'gaps' using Gaussian Adaptive Thresholding. selection_small = WindowManager.getImage("subsection_small.tif") IJ.run(selection_small, "Duplicate...", "title=thresholded.tif") threshed = WindowManager.getImage("thresholded.tif") IJ.run(threshed, "Auto Local Threshold", "method=Bernsen radius=7 parameter_1=1 parameter_2=0 white") # Select the TTs from the thresholded image. IJ.run(threshed, "Create Selection", "") tt_selection = WindowManager.getImage("subsection_small.tif") IJ.selectWindow("thresholded.tif") IJ.selectWindow("subsection_small.tif") IJ.run(tt_selection, "Restore Selection", "") # Get TT intensity statistics. stat_options = IS.MEAN | IS.MIN_MAX | IS.STD_DEV stats = IS.getStatistics(tt_selection.getProcessor(), stat_options, selection_small.getCalibration()) # Calculate pixel ceiling intensity value based on heuristic. # TODO: Add a catch for data type overflow. pixel_ceiling = stats.mean + 3 * stats.stdDev print "px ceil:", pixel_ceiling # Invert selection to get inter-sarcomeric gap intensity statistics. IJ.run(tt_selection, "Make Inverse", "") stat_options = IS.MEAN | IS.MIN_MAX | IS.STD_DEV stats = IS.getStatistics(tt_selection.getProcessor(), stat_options, selection_small.getCalibration()) # Calculate pixel floor intensity value based on heuristic. pixel_floor = stats.mean - stats.stdDev # TODO: Add a catch for data type underflow. print "px floor:", pixel_floor # Threshold original image based on these values. IJ.selectWindow(this_img.getTitle()) IJ.run(this_img, "Select All", "") IJ.setMinAndMax(pixel_floor, pixel_ceiling) IJ.run(this_img, "Apply LUT", "") ## Ask if it is acceptable. gd = GenericDialog("Acceptable?") gd.addMessage( "If the preprocessed image is acceptable for analysis, hit 'OK' to being analysis.\n" + " If the image is unacceptable or an error occurred, hit 'Cancel'") gd.showDialog() if gd.wasCanceled(): return ## Save the preprocessed image. imp = IJ.getImage() fs = FileSaver(imp) img_save_dir = matchedmyo_path + "myoimages/" # actually get from user at some point img_file_path = img_save_dir + img_name[:-4] + "_preprocessed.tif" if os.path.exists(img_save_dir) and os.path.isdir(img_save_dir): print "Saving image as:", img_file_path if os.path.exists(img_file_path): # use dialog box to ask if they want to overwrite gd = GenericDialog("Overwrite?") gd.addMessage( "A file exists with the specified path, \"{}\". Would you like to overwrite it?" .format(img_file_path)) gd.enableYesNoCancel() gd.showDialog() if gd.wasCanceled(): return elif fs.saveAsTiff(img_file_path): print "Preprocessed image saved successfully at:", '"' + img_file_path + '"' else: print "Folder does not exist or is not a folder!" ### Create the YAML file containing the parameters for classification ## Ask user for YAML input gd = GenericDialog("YAML Input") gd.addStringField("imageName", img_file_path, 50) #gd.addStringField("maskName", "None") gd.addStringField("outputParams_fileRoot", img_file_path[:-4], 50) gd.addStringField("outputParams_fileType", "tif") gd.addNumericField("outputParams_dpi", 300, 0) gd.addCheckbox("outputParams_saveHitsArray", False) gd.addStringField("outputParams_csvFile", matchedmyo_path + "results/") gd.addCheckbox("TT Filtering", True) gd.addToSameRow() gd.addCheckbox("LT Filtering", True) gd.addToSameRow() gd.addCheckbox("TA Filtering", True) gd.addNumericField("scopeResolutions_x", 5.0, 3) gd.addToSameRow() gd.addNumericField("scopeResolutions_y", 5.0, 3) gd.addMessage("Enter in filter rotation angles separated by commas.") gd.addStringField("", "-25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25", 50) gd.addCheckbox("returnAngles", False) gd.addCheckbox("returnPastedFilter", True) gd.showDialog() if gd.wasCanceled(): return strings = [st.text for st in gd.getStringFields()] #if strings[1] == "None" or "": # strings[1] = None nums = [float(num.text) for num in gd.getNumericFields()] nums[0] = int(nums[0]) # Have to make sure the dpi variable is an integer checks = [str(bool(boo.state)) for boo in gd.getCheckboxes()] iter_argument = ','.join( [str(float(it) - rotation_angle) for it in strings[4].split(',')]) string_block = """imageName: {0[0]} outputParams: fileRoot: {0[1]} fileType: {0[2]} dpi: {1[0]} saveHitsArray: {2[0]} csvFile: {0[3]} preprocess: False filterTypes: TT: {2[1]} LT: {2[2]} TA: {2[3]} scopeResolutions: x: {1[1]} y: {1[2]} iters: [{3}] returnAngles: {2[4]} returnPastedFilter: {2[5]}""".format(strings, nums, checks, iter_argument) im_title = this_img.getTitle() with cd(matchedmyo_path): yaml_file_path = "./YAML_files/" + im_title[:-4] + ".yml" with open("./YAML_files/" + im_title[:-4] + ".yml", "w") as ym: ym.write(string_block) print "Wrote YAML file to:", matchedmyo_path + yaml_file_path[2:] ### Run the matchedmyo code on the preprocessed image with cd(matchedmyo_path): #os.chdir(matchedmyo_path) #subprocess.call(["python3", matchedmyo_path+"matchedmyo.py", "fullValidation"]) subprocess.call( ["python3", "matchedmyo.py", "run", "--yamlFile", yaml_file_path])
#print(image.getTitle()) #define minimum separation between beads using the existing calibration (currently equivalent to 15px) min_separation = 15 * image.getCalibration().getX(1) # initialise variables for calculating in-focus slice maxstddev = 0 infocus = 0 # now we go through the original image and retrieve slices to # detect the maximum st dev for in-focus slice for i in range(1, image.getNSlices() + 1): myslice = stack.getProcessor(i) stats = IS.getStatistics(myslice) #print(stats.stdDev) if stats.stdDev > maxstddev: maxstddev = stats.stdDev infocus = i #print(i,infocus,maxstddev) # we set the relevant z-slice to be the maximum std dev one and get # that stack (multiple channels) IJ.run("Duplicate...", "duplicate slices=" + str(infocus)) im_slice = IJ.getImage() # make sure the results window is clear IJ.run("Clear Results")
# use centre of mass to locate film, use http://imagej.net/developer/api/ij/process/ImageStatistics.html from ij import IJ from ij.process import ImageStatistics as IS from ij.process import ImageProcessor from ij.measure import Measurements as Measure imp = IJ.openImage("C:\\Users\\RCole02\\Desktop\\images\\wrong.JPG") imp.show() if imp.height > imp.width: IJ.run(imp, "Rotate 90 Degrees Right", "") print "image now horizontal" ip = imp.getProcessor() stats = IS.getStatistics(ip, Measure.CENTER_OF_MASS, imp.getCalibration()) print "xCenterOfMass: " + str(stats.xCenterOfMass) + "yCenterOfMass: " + str(stats.yCenterOfMass) if stats.yCenterOfMass < 0.5*imp.height: IJ.run(imp, "Flip Vertically", "")
# 이미지 통계 정보 추출 from ij import IJ from ij.process import ImageStatistics as IS # 떠 있는 이미지 캡처 imp = IJ.getImage() # ImagePlus : title, dimension 등 이미지 정보를 포함. # ImageProcessor 호출 # ImageProcessor : ImagePlus 중 2D Image 부분 + 조작을 위한 기본 methods. ImageStack (3D 이상) 제외 # ImagePlus & ImageProcessor: https://javadoc.scijava.org/ImageJ1/ij/ImagePlus.html ip = imp.getProcessor() options = IS.MEAN | IS.MEDIAN | IS.MIN_MAX # getStatistics: Calculates and returns uncalibrated (raw) statistics for the specified image, including histogram, area, mean, min and max, standard deviation and mode. # IS.getStatistics: https://imagej.nih.gov/ij/developer/api/ij/process/ImageStatistics.html#getStatistics-ij.process.ImageProcessor-int-ij.measure.Calibration- stats = IS.getStatistics(ip, options, imp.getCalibration()) # 통계 데이터 출력 print "Image statistics for", imp.title print "Mean:", stats.mean print "Median:", stats.median print "Min and max:", stats.min, "-", stats.max
# autothreshold using the Triangle method and get the thresholds imp_mip.setAutoThreshold(AutoThresholder.Method.Triangle,True) mint = imp_mip.getMinThreshold() maxt = imp_mip.getMaxThreshold() # we don't need the MIP anymore imp_mi.close() # For each channel, get the mean value above threshold and store it profile=[] for ich in range(imp.getNChannels()): p = imp.getStack().getProcessor(ich+1) p.setThreshold(mint,maxt,0) stats = ImageStatistics.getStatistics(p, ImageStatistics.MEAN | ImageStatistics.LIMIT, None) v = stats.mean # Deal with cases where no pixel is abote threshold if isnan(v): v = 0 profile.append(v) xml+="<Ch%d>%f</Ch%d>"%(ich+1,v,ich+1) profiles.append(profile) xml+="</Dye%d>"%(idye) imp.close()