def analyzeTUB(): rm = RoiManager().getInstance() #Set imageJ preference meassurements to "area" IJ.run("Set Measurements...", "area display redirect=None decimal=3") #Variable used for iteration counter = 0 #Clear previous resuslts IJ.run("Clear Results") # Make library, to be iterated through. Room for improvement lis_dic = [{'path': sub[i]} for i in range(len(sub))] if not lis_dic: sys.exit('Did you check the right box?') # Calculate area of channel #1 (Calculation requires that area is chosen as measured value) for i in lis_dic: print i for p in data[counter][::-1]: print p if '_' + channel1 + '_' in p: imp1 = IJ.openImage(i['path'] + '/' + p) IJ.setThreshold(imp1, lowth1, 255) IJ.run(imp1, "Create Selection", "") roi = rm.getRoi(imp1) #rm.runCommand(imp1, 'Add') IJ.run(imp1, "Measure", "") if '_' + channel2 + '_' in p: imp2 = IJ.openImage(i['path'] + '/' + p) IJ.setThreshold(imp2, lowth2, 255) rm.runCommand(imp1, 'Select') IJ.run(imp2, "Analyze Particles...", "size=0-4000 summarize") counter += 1 # Reset counter counter = 0 IJ.renameResults(channel2)
def main(parentpath, cellNo): rootname = "cell" + str(cellNo) roizipname = 'RoiSet_' + rootname + '.zip' imagename = rootname + '_virus_median.tif' #pp = '/Users/miura/Desktop/161122 ctrl croped and 16 frames/RoiSet_cell5.zip' # unzipping http://stackoverflow.com/questions/3451111/unzipping-files-in-python #pp = '/Users/miura/Desktop/161122 ctrl croped and 16 frames/RoiSet_cell5/0005-0419-0327.roi' zippp = os.path.join(parentpath, roizipname) rm = RoiManager(False) rm.runCommand("Open", zippp) cellroi = rm.getRoi(2) if cellroi.getType() != 3: print "ROI type mismatch! ... ABORT" sys.exit() #imagepath = '/Users/miura/Desktop/161122 ctrl croped and 16 frames/cell1_virus_median.tif' imagepath = os.path.join(parentpath, imagename) tracks, cellarea, postcounts, postcounts2, precounts, imp, reallength, secondFrameVirusCounts = core(cellroi, imagepath) return tracks, cellarea, postcounts, postcounts2, precounts, imp, reallength, secondFrameVirusCounts
# make paths for moving when done. full_img_path_orig = os.path.join(blinded_base, image_title + ".tif") full_img_path_done = os.path.join(data, image_title + ".tif") # get roi manager roim = RoiManager().getRoiManager() # make savepaths for csv and rois roimsave = os.path.join(data, image_title + "_rois.zip") csvsave = os.path.join(data, image_title + "_data.csv") csv_ = [["image", "roi_name", "uncalibrated_length"]] for roi, _ in enumerate(roim.getRoisAsArray()): target = roim.getRoi(roi) csv_.append([image_title, target.getName(), target.getLength()]) # write and save csv with open(csvsave, "w") as c: writer = csv.writer(c) for l in csv_: writer.writerow(l) # save rois roim.runCommand("Deselect") roim.runCommand("Save", roimsave) # close both roim.close() img.close()
def generate_background_rois(input_mask_imp, params, membrane_edges, dilations=5, threshold_method=None, membrane_imp=None): """automatically identify background region based on auto-thresholded image, existing membrane edges and position of midpoint anchor""" if input_mask_imp is None and membrane_imp is not None: segmentation_imp = Duplicator().run(membrane_imp) # do thresholding using either previous method if threhsold_method is None or using (less conservative?) threshold method if (threshold_method is None or not (threshold_method in params.listThresholdMethods())): mask_imp = make_and_clean_binary(segmentation_imp, params.threshold_method) else: mask_imp = make_and_clean_binary(segmentation_imp, threshold_method) segmentation_imp.close() else: input_mask_imp.killRoi() mask_imp = Duplicator().run(input_mask_imp) rois = [] IJ.setForegroundColor(0, 0, 0) roim = RoiManager(True) rt = ResultsTable() for fridx in range(mask_imp.getNFrames()): mask_imp.setT(fridx + 1) # add extra bit to binary mask from loaded membrane in case user refined edges... # flip midpoint anchor across the line joining the two extremes of the membrane, # and fill in the triangle made by this new point and those extremes poly = membrane_edges[fridx].getPolygon() l1 = (poly.xpoints[0], poly.ypoints[0]) l2 = (poly.xpoints[-1], poly.ypoints[-1]) M = (0.5 * (l1[0] + l2[0]), 0.5 * (l1[1] + l2[1])) Mp1 = (params.manual_anchor_midpoint[0][0] - M[0], params.manual_anchor_midpoint[0][1] - M[1]) p2 = (M[0] - Mp1[0], M[1] - Mp1[1]) new_poly_x = list(poly.xpoints) new_poly_x.append(p2[0]) new_poly_y = list(poly.ypoints) new_poly_y.append(p2[1]) mask_imp.setRoi(PolygonRoi(new_poly_x, new_poly_y, PolygonRoi.POLYGON)) IJ.run(mask_imp, "Fill", "slice") mask_imp.killRoi() # now dilate the masked image and identify the unmasked region closest to the midpoint anchor ip = mask_imp.getProcessor() dilations = 5 for d in range(dilations): ip.dilate() ip.invert() mask_imp.setProcessor(ip) mxsz = mask_imp.getWidth() * mask_imp.getHeight() pa = ParticleAnalyzer( ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.SHOW_PROGRESS, ParticleAnalyzer.CENTROID, rt, 0, mxsz) pa.setRoiManager(roim) pa.analyze(mask_imp) ds_to_anchor = [ math.sqrt((x - params.manual_anchor_midpoint[0][0])**2 + (y - params.manual_anchor_midpoint[0][1])**2) for x, y in zip( rt.getColumn(rt.getColumnIndex("X")).tolist(), rt.getColumn(rt.getColumnIndex("Y")).tolist()) ] if len(ds_to_anchor) > 0: roi = roim.getRoi(ds_to_anchor.index(min(ds_to_anchor))) rois.append(roi) else: rois.append(None) roim.reset() rt.reset() roim.close() mask_imp.close() return rois
# Some of the parameters we configure below need to have # a reference to the model at creation. So we create an # empty model now. model = Model(); # Send all messages to ImageJ log window. model.setLogger(Logger.IJ_LOGGER); model.setPhysicalUnits(Calib.getUnit(), Calib.getTimeUnit()); #------------------------ # Prepare settings object #------------------------ settings = Settings(); rm.select(imp,idx); actual_roi = rm.getRoi(idx); imp.setRoi(actual_roi); settings.setFrom(imp); settings.tstart = Initial_frames; settings.tend = imp.getNFrames() - Final_frames -1; #settings.roi = rm.getSelectedRoisAsArray(); # Configure detector - We use the Strings for the keys settings.detectorFactory = LogDetectorFactory(); settings.detectorSettings = { 'DO_SUBPIXEL_LOCALIZATION' : Subpixel_localization, 'RADIUS' : Spot_radius, 'TARGET_CHANNEL' : 1, 'THRESHOLD' : Intensity_threshold, 'DO_MEDIAN_FILTERING' : Median_filtering, };
def Overlayer(org_size, dirs): """ Overlays ROIs with appropriate color, saves to .tif and animates aligned images to .gif """ # Get colors. Colors, Colors_old = colorlist() # Get ROImanager. rm = RoiManager().getInstance() rois = rm.getCount() # Overlays ROI on aligned images, converts to 8-bit (for gif). for root, directories, filenames in os.walk(dirs["Composites_Aligned"]): for filename in filenames: imp = IJ.openImage(os.path.join(root, filename)) converter = ImageConverter(imp) converter.setDoScaling(True) converter.convertToGray8() # Lookup table and local contrast enhancement for vizualisation. IJ.run(imp, "Rainbow RGB", "") IJ.run(imp, "Enhance Local Contrast (CLAHE)", "blocksize=127 histogram=256 maximum=3 mask=*None*") for roi in range(rois): roi_obj = rm.getRoi(roi) roi_obj.setStrokeWidth(2) if roi < 19: roi_obj.setStrokeColor(Color(*Colors[roi][0:3])) else: roi_obj.setStrokeColor(eval(Colors_old[roi])) rm.moveRoisToOverlay(imp) IJ.saveAs(imp, "Tiff", os.path.join(dirs["Overlays"], filename)) # Opens overlaid images, saves as tiff stack. overlay_stack = IJ.run("Image Sequence...", "open="+dirs["Overlays"]+ " number=3040 starting=0 increment=1 scale=300 file=.tif sort") # Takes care of spaces in titles. tiftitle = Title.replace(" ", "_") tiftitle = tiftitle.replace(".", "_") # Gets dimensions for scalebar. imp = WindowManager.getImage("Overlays") dimensions = imp.getDimensions() size = dimensions[0] + dimensions[1] microns = org_size / size # Sets scale and writes scale-bar, flattens overlays. IJ.run(imp, "Set Scale...", "distance=1 known=" +str(microns)+" pixel=1 unit=micron") IJ.run(imp, "Scale Bar...", "width=10 height=4 font=14 color=Yellow background=None location=[Lower Right] bold overlay") IJ.run(imp, "Flatten", "stack") IJ.saveAs(imp, "Tiff", os.path.join(dirs["Gifs"], tiftitle)) # Animates tiff stack from directoy. for root, directories, filenames in os.walk(dirs["Gifs"]): for filename in filenames: if tiftitle in filename and filename.endswith(".tif"): # set=xx parameter controls gif speed. # for additional parameters run with macro recorder. try: print "Animating gif..." imp = WindowManager.getImage(tiftitle + ".tif") gif = IJ.run("Animated Gif ... ", "set=200 number=0 filename=" + os.path.join(dirs["Gifs"], tiftitle + ".gif")) except Exception, e: print str(e) print "gif animated."
def tethered_cell(image_path, frame_number=100, frame_rate=100.0, CCW=1): """ parameter setting; frame rate (frame/sec) CCW = 1 : the motor rotation direction and the cell rotation direction on the image are same CCW = -1: the motor rotation direction and the cell rotation direction on the image are different """ opener = Opener() imp = opener.openImage(image_path) image_slice_number = imp.getNSlices() rm = RoiManager().getInstance() if image_slice_number < frame_number: # too short movie IJ.log('Number of frame of the movie is fewer than the number of frame that you selected') return False # create result directory result_path = image_path + '_tethered_cell_result' if os.path.lexists(result_path) is False: os.mkdir(result_path) #z projection; standard deviation, tethered cell shorws circle IJ.run(imp, 'Subtract Background...', 'rolling=5 light stack') IJ.run(imp, 'Median...', 'radius=2 stack') IJ.run(imp, 'Z Project...', 'stop=500 projection=[Standard Deviation]') zimp = IJ.getImage() IJ.saveAs(zimp, 'bmp', os.path.join(result_path,'STD_DEV.bmp')) # pick up tethered cell IJ.setAutoThreshold(zimp, 'MaxEntropy dark') IJ.run(zimp, 'Convert to Mask', '') IJ.run('Set Measurements...', "area centroid bounding shape feret's limit redirect=None decimal=3") IJ.run(zimp, 'Analyze Particles...', 'size=30-Infinity circularity=0.88-1.00 show=Nothing display exclude clear include') zrt = ResultsTable.getResultsTable() IJ.saveAs('Results', os.path.join(result_path,'RoiInfo.csv')) #tcX and tcY are xy coordinates of tethered cell, tcdia is outer diameter of rotating tethered cell #add ROI into stack image for i in range(zrt.getCounter()): tcX = zrt.getValue('X', i) tcY = zrt.getValue('Y', i) tcdia = zrt.getValue('Feret', i) rm.add(imp, OvalRoi(tcX - tcdia/2.0, tcY - tcdia/2.0, tcdia + 1, tcdia + 1), i) #calculate rotation speed by ellipse fitting IJ.setAutoThreshold(imp, 'Li') for roi_number in range(rm.getCount()): t = [] XM = [] YM = [] theta = [] rotation_speed = [] area = [] imp.setRoi(rm.getRoi(roi_number)) cropped_imp = Duplicator().run(imp) IJ.run('Set Measurements...', 'area mean center fit limit redirect=None decimal=3') rm.select(roi_number) rt = rm.multiMeasure(imp) # check cell is present while analysis. Don't a cell gose anywhare? for i in range(frame_number): area.append(rt.getValue('Area1', i)) if 0 in area: continue for i in range(frame_number): t.append((1/frame_rate)*i) XM.append(rt.getValue('XM1', i)) YM.append(rt.getValue('YM1', i)) theta.append(rt.getValue('Angle1', i)/180.0*math.pi) # convert to radian if i == 0: rotation_speed.append(0) else: # phase treatment, theta should be -pi ~ pi temp_rotation_speed = [theta[i] - theta[i-1], theta[i] - theta[i-1] + math.pi, theta[i] - theta[i-1] - math.pi, theta[i] - theta[i-1] + 2*math.pi, theta[i] - theta[i-1] - 2*math.pi] temp_rotation_speed = sorted(temp_rotation_speed, key = lambda x :abs(x) )[0] rotation_speed.append(CCW*temp_rotation_speed/(2.0*math.pi)*frame_rate) # write csv # earch columns indicate 1:index, 2:time(sec), 3:X-coordinate of center of mass(pixel), 4:Y-coordinate of center of mass (pixel), 5:Angle(Radian), 6:Rotation Speed(Hz) with open(os.path.join(result_path,'Roi' + str(roi_number) + '.csv'), 'w') as f: writer = csv.writer(f) writer.writerow(['Index', 'time(s)', 'X', 'Y', 'Angle(rad)', 'Rotation Speed(Hz)']) for i in range(len(t)): writer.writerow([i, t[i], XM[i], YM[i], theta[i], rotation_speed[i]]) # plot x-y, t-x, t-y, t-rotation speed, save plot as bmp plotRotation(roi_number, result_path, t, XM, YM, rotation_speed) IJ.saveAs(cropped_imp, 'tiff', os.path.join(result_path,'Roi' + str(roi_number) + '.tiff')) rt.reset() # get analysis date and time dt = datetime.datetime.today() dtstr = dt.strftime('%Y-%m-%d %H:%M:%S') # wtite analysis setting with open(os.path.join(result_path,'analysis_setting.csv'), 'w') as f: writer = csv.writer(f) writer.writerow(['Analysis Date','frame number','frame rate','CCW direction', 'Method','Auto threshold', 'Subtruct Background', 'Median filter']) writer.writerow([dtstr, frame_number, frame_rate, CCW, 'Ellipse', 'Li', '5.0', '2']) # save roi if rm.getCount() != 0: rm.runCommand('Save', os.path.join(result_path, 'Roi.zip')) zimp.close() imp.close() rm.close() zrt.reset()