def getCroppedChannels(self, imp, cell): splitter = ChannelSplitter() imp.setRoi(None) if cell.mode3D: cropRoi = cell.getCropRoi() else: cropRoi = cell.roi if cropRoi is None: return None crop = cropRoi.getBounds() channels = [] for c in range(1, imp.getNChannels() + 1): slices = ImageStack(crop.width, crop.height) channel = splitter.getChannel(imp, c) for z in range(1, channel.getSize() + 1): zslice = channel.getProcessor(z) zslice.setRoi(cropRoi) nslice = zslice.crop() if cell.mode3D: oroi = cell.slices[z - 1].roi else: oroi = cell.roi if oroi is not None: roi = oroi.clone() bounds = roi.getBounds() roi.setLocation(bounds.x - crop.x, bounds.y - crop.y) nslice.setColor(Color.black) nslice.fillOutside(roi) slices.addSlice(nslice) channels.append(ImagePlus("Channel %i" % c, slices)) return channels
def previewImage(self, imp): roi = imp.getRoi() splitter = ChannelSplitter() channels = [] for c in range(1, imp.getNChannels() + 1): channel = ImagePlus("Channel %i" % c, splitter.getChannel(imp, c)) projector = ZProjector(channel) projector.setMethod(ZProjector.MAX_METHOD) projector.doProjection() channels.append(projector.getProjection()) image = RGBStackMerge.mergeChannels(channels, False) image.title = imp.title + " MAX Intensity" image.luts = imp.luts imp.setRoi(roi) return image
def getPreview(image): enhancer = ContrastEnhancer() projector = ZProjector() splitter = ChannelSplitter() imp1 = ImagePlus("CH1", ) width, height, channels, slices, frames = image.getDimensions() chimps = [] for ch in range(1, channels + 1): projector = ZProjector(ImagePlus("C%i" % ch, splitter.getChannel(image, ch))) projector.setMethod(ZProjector.MAX_METHOD) projector.doProjection() proj = projector.getProjection() enhancer.equalize(proj) chimps.append(proj) return RGBStackMerge.mergeChannels(chimps, False)
def main(): # Open a .ome.tif image from the Flexoscope. impath = IJ.getFilePath("Choose .ome.tiff file") channels = Opener.openUsingBioFormats(impath) cal = channels.getCalibration() # Show image # imp.show() # straight to channels object sames memory. # Split channels. channels = ChannelSplitter().split(channels) # Process channel 1. # subtractzproject(imp, projectionMethod="Median") channels[0] = subtractzproject(channels[0]) IJ.run(channels[0], "8-bit", "") # Process channel 2. # glidingprojection(imp, startframe=1, stopframe=None, glidingFlag=True, no_frames_per_integral=3, projectionmethod="Median") channels[1] = glidingprojection(channels[1]) IJ.run(channels[1], "8-bit", "") # [Optional] Process channel 3, 4, etc. # subtractzproject(channels[3], projectionMethod="Median") # glidingprojection(channels[3], startframe=1, stopframe=None, glidingFlag=True, no_frames_per_integral=3, projectionmethod="Median") # IJ.run(channels[3], "8-bit", "") # Merge channels. merge = RGBStackMerge().mergeChannels(channels, True) # boolean keep merge.setCalibration(cal) merge.show()
def split_channels_blue(imp): #Create blue channel original_blue = ChannelSplitter.getChannel(imp, 3) original_blue_IP = ImagePlus(filename, original_blue) fs = FileSaver(original_blue_IP) folder = "/Users/gceleste/Desktop/test/channels" filepath = folder + "/" + "{}_bluechannel.tif".format(filename) fs.saveAsTiff(filepath) #Open blue channel image. blue = IJ.open(filepath) #blue_IP = ImagePlus(filename, blue) IJ.run( "3D Objects Counter", "threshold=100 slice=1 min.=50 max.=1447680 exclude_objects_on_edges objects summary" ) #Save blue object map blue_map = IJ.getImage() fs = FileSaver(blue_map) folder = "/Users/gceleste/Desktop/test/object maps" filepath = folder + "/" + "{}_objectmap(blue).jpg".format(filename) fs.saveAsJpeg(filepath) #Close blue channel image. blue_map.close() blue = IJ.getImage() blue.close()
def gfp_analysis(imp, file_name, output_folder): """perform analysis based on gfp intensity thresholding""" cal = imp.getCalibration() channel_imps = ChannelSplitter.split(imp) gfp_imp = channel_imps[0] gfp_imp.setTitle("GFP") threshold_imp = Duplicator().run(gfp_imp) threshold_imp.setTitle("GFP_threshold_imp") ecad_imp = channel_imps[1] ecad_imp.setTitle("E-cadherin") nuc_imp = channel_imps[2] IJ.run(threshold_imp, "Make Binary", "method=Otsu background=Dark calculate") IJ.run(threshold_imp, "Fill Holes", "") erode_count = 2 for _ in range(erode_count): IJ.run(threshold_imp, "Erode", "") threshold_imp = keep_blobs_bigger_than(threshold_imp, min_size_pix=1000) threshold_imp = my_kill_borders(threshold_imp) rois = generate_cell_rois(threshold_imp) out_stats = generate_cell_shape_results(rois, gfp_imp, cal, file_name) print("Number of cells identified = {}".format(len(out_stats))) threshold_imp.changes = False threshold_imp.close() # save output save_qc_image( imp, rois, "{}_plus_overlay.tiff".format( os.path.join(output_folder, os.path.splitext(file_name)[0]))) save_cell_rois(rois, output_folder, os.path.splitext(file_name)[0]) imp.changes = False imp.close() save_output_csv(out_stats, output_folder) return out_stats
def splitchannel(imp, chindex): nch = imp.getNChannels() print('Number of Channels: ' + str(nch)) if chindex > nch: # if nch > 1: print('Fallback : Using Channel 1') chindex = 1 imps = ChannelSplitter.split(imp) imp = imps[chindex - 1] if chindex <= nch: imps = ChannelSplitter.split(imp) imp = imps[chindex - 1] return imp
def split_channels_red(imp): #Create red channel original_red = ChannelSplitter.getChannel(imp, 1) original_red_IP = ImagePlus(filename, original_red) fs = FileSaver(original_red_IP) folder = "/Users/gceleste/Desktop/test/channels" filepath = folder + "/" + "{}_redchannel.tif".format(filename) fs.saveAsTiff(filepath) #Open red channel image. red = IJ.open(filepath) #red_IP = ImagePlus(filename, red) IJ.run( "3D Objects Counter", "threshold=130 slice=1 min.=50 max.=1447680 exclude_objects_on_edges objects summary" ) #Save red object map. red_map = IJ.getImage() fs = FileSaver(red_map) folder = "/Users/gceleste/Desktop/test/object maps" filepath = folder + "/" + "{}_objectmap(red).jpg".format(filename) fs.saveAsJpeg(filepath) #Close red channel images. red_map.close() red = IJ.getImage() red.close()
def pre_process_images(image_input, timepoints): #correct drift IJ.run( image_input, "Properties...", "channels=2 slices=1 frames=" + str(timepoints) + " unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000" ) corrected_img = run_3d_drift_correct(image_input) #split channels red_corrected_img, phase_corrected_img = ChannelSplitter.split( corrected_img) #get image dimensions, set ROI remove part of flouresncent ring x_size = ImagePlus.getDimensions(red_corrected_img)[0] y_size = ImagePlus.getDimensions(red_corrected_img)[1] x_start = 0 y_start = 0 red_corrected_img.setRoi(OvalRoi(x_start, y_start, x_size, y_size)) IJ.run(red_corrected_img, "Make Inverse", "") IJ.setForegroundColor(0, 0, 0) IJ.run(red_corrected_img, "Fill", "stack") red_corrected_img.killRoi() #correcting background IJ.run( red_corrected_img, "Properties...", "channels=1 slices=" + str(timepoints) + " frames=1 unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000" ) #red_corrected_background_img = apply_rollingball(red_corrected_img, 7.0, False, False,False, False, False) testset = basic.BaSiCSettings() testset.imp = red_corrected_img testset.myShadingEstimationChoice = "Estimate shading profiles" testset.myShadingModelChoice = "Estimate both flat-field and dark-field" testset.myParameterChoice = "Manual" testset.lambda_flat = 2.0 testset.lambda_dark = 2.0 testset.myDriftChoice = "Replace with zero" testset.myCorrectionChoice = "Compute shading and correct images" test = basic.BaSiC(testset) test.run() red_corrected_background_img = test.getCorrectedImage() #change properties back and perform bleach correction IJ.run( red_corrected_background_img, "Properties...", "channels=1 slices=1 frames=" + str(timepoints) + " unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000" ) red_corrected_background_img_dup = red_corrected_background_img.duplicate() corrected_bleach = BleachCorrection_MH(red_corrected_background_img) corrected_bleach.doCorrection() return (red_corrected_background_img_dup, red_corrected_background_img)
def get_analysis_ch(imp, analysis_ch): ''' Returns an ImagePlus of the channel index specified in analysis_ch ''' from ij.plugin import ChannelSplitter analysis_imp = ChannelSplitter.split(imp)[analysis_ch-1] return analysis_imp
def downsample_for_isotropy(imp, extra_downsample_factor=2.0, info=None): """downsample x, y pixel directions to get ~cubic voxels""" title = imp.getTitle(); cal = imp.getCalibration(); if info is None: pix_w = cal.pixelWidth; pix_h = cal.pixelHeight; pix_d = cal.pixelDepth; else: pix_w = info.get_xy_pixel_size_um(); pix_h = pix_w; pix_d = info.get_z_plane_spacing_um(); im_w = imp.getWidth(); im_h = imp.getHeight(); im_d = imp.getNSlices(); print("original pixel whd = ({}, {}, {})".format(pix_w, pix_h, pix_d)); print("original image whd = ({}, {}, {})".format(im_w, im_h, im_d)); im_nch = imp.getNChannels(); if im_nch > 1: split_ch = ChannelSplitter().split(imp); else: split_ch = [imp]; print("downsampling {} and making isotropic...".format(title)); IJ.showStatus("Downsampling and making ~isotropic..."); xy_scale = pix_h / (pix_d * extra_downsample_factor); xy_scaled_h = int(xy_scale * im_h); xy_scaled_w = int(xy_scale * im_w); z_scale = 1/ extra_downsample_factor; z_scaled_h = int(z_scale * im_d); out_imps = []; for ch_imp in split_ch: print(ch_imp.getTitle()); sp = StackProcessor(ch_imp.getStack()); print((xy_scaled_w, xy_scaled_h)); stack = sp.resize(xy_scaled_w, xy_scaled_h, True); xz_stack = rot_around_x(stack); xz_sp = StackProcessor(xz_stack); xz_stack = xz_sp.resize(xy_scaled_w, z_scaled_h, True); out_stack = rot_around_x(xz_stack); out_imps.append(ImagePlus("Isotropic downsampled {}".format(title), out_stack)); cal.setUnit('um'); cal.pixelWidth = im_w/xy_scaled_w * pix_w; cal.pixelHeight = im_h/xy_scaled_h * pix_h; cal.pixelDepth = im_d/z_scaled_h * pix_d; print("new pixel whd = ({}, {}, {})".format(cal.pixelWidth, cal.pixelHeight, cal.pixelDepth)); imp.changes = False; imp.close(); for ch_imp in split_ch: ch_imp.close(); if len(out_imps) > 1: out_imp = RGBStackMerge().mergeChannels(out_imps, False); else: out_imp = out_imps[0]; out_imp.setCalibration(cal); print("new image whd = ({}, {}, {})".format(out_imp.getWidth(), out_imp.getHeight(), out_imp.getNSlices())); print("...done downsampling {} and making isotropic. ".format(title)); IJ.showStatus("...done downsampling and making ~isotropic. "); return out_imp;
def measure(cell): print "Opening", cell.getPpcdImageFilePath() imp = Opener().openImage(cell.getPpcdImageFilePath()) # open preprocessed Image imps = ChannelSplitter.split(imp) a = ATA() a.setSilent(True) a.segAndMeasure(imps[0], imps[1]) results = a.getLinkedArray() print results
def split_image(file_): print "Processing: %s" %(basename(file_)) #load with loci (allows also to load *.czi) images = BF.openImagePlus(file_) image = images[0] #split channels chSp = ChannelSplitter() title = splitext(image.title)[0] imageC = chSp.split(image) print "Number of channels: ", len(imageC) for iCh in range(0, len(imageC)): imageStack = imageC[iCh].getImageStack() for iSlice in range(0,imageC[0].getNSlices()): #print iSlice impOut = ImagePlus("outImg", imageStack.getProcessor(iSlice+1)) ntitle = to_wellbased_nameing_scheme(title, iCh+1, iSlice+1) IJ.log("Image: %s -> %s " %(title, ntitle)) IJ.saveAs(impOut, "Tiff", join(outdir, ntitle) )
def manual_analysis(imp, file_name, output_folder, gfp_channel_number=1, dapi_channel_number=3, red_channel_number=2, important_channel=1): """perform analysis based on manually drawn cells""" try: cal = imp.getCalibration() channel_imps = ChannelSplitter.split(imp) intensity_channel_imp = channel_imps[important_channel - 1] nuc_imp = channel_imps[dapi_channel_number - 1] nuclei_locations, full_nuclei_imp, _ = get_nuclei_locations( nuc_imp, cal, distance_threshold_um=10, size_threshold_um2=100) full_nuclei_imp.hide() rois = perform_manual_qc(imp, [], important_channel=important_channel) no_nuclei_centroids = [ get_no_nuclei_in_cell(roi, nuclei_locations) for roi in rois ] no_enclosed_nuclei = [ get_no_nuclei_fully_enclosed(roi, full_nuclei_imp) for roi in rois ] full_nuclei_imp.changes = False full_nuclei_imp.close() out_stats = generate_cell_shape_results( rois, intensity_channel_imp, cal, file_name, no_nuclei_centroids=no_nuclei_centroids, no_enclosed_nuclei=no_enclosed_nuclei) if gfp_channel_number is None: for idx, cell_shape_result in enumerate(out_stats): cell_shape_result.cell_gfp_I_mean = 0 cell_shape_result.cell_gfp_I_sd = 0 out_stats[idx] = cell_shape_result print("Number of cells identified = {}".format(len(out_stats))) for ch in range(imp.getNChannels()): imp.setC(ch + 1) IJ.run(imp, "Enhance Contrast", "saturated={}".format(0.35)) # save output save_qc_image( imp, rois, "{}_plus_overlay.tiff".format( os.path.join(output_folder, os.path.splitext(file_name)[0]))) save_cell_rois(rois, output_folder, os.path.splitext(file_name)[0]) imp.changes = False imp.close() save_output_csv(out_stats, output_folder) except Exception as e: print("Ran into a problem analysing {}: {}. Skipping to next cell...". format(file_name, e.message)) out_stats = [] return out_stats
def rot3d(imp, axis='x'): """pare back Slicer to implement whole-image, +90* rotations that return ImagePlus""" if imp.getType()==ImagePlus.COLOR_256 or imp.getType()==ImagePlus.COLOR_RGB: raise NotImplementedError("Handling of colour images isn't implemented yet"); IJ.showStatus("Rotating around {}-axis...".format(axis)) title = imp.getTitle(); original_cal = imp.getCalibration(); new_cal = original_cal; if imp.getNChannels > 1: split_ch = ChannelSplitter().split(imp); else: split_ch = [imp]; out_imps = []; if axis=='x': for ch_imp in split_ch: input_stack = ch_imp.getStack(); output_stack = rot_around_x(input_stack); out_imps.append(ImagePlus(title, output_stack)); new_cal.pixelHeight = original_cal.pixelDepth; new_cal.pixelDepth = original_cal.pixelHeight; elif axis=='y' or axis=='-y': for ch_imp in split_ch: if axis[0]=='-': input_stack = StackProcessor(ch_imp.getStack()).rotateLeft(); else: input_stack = StackProcessor(ch_imp.getStack()).rotateRight(); output_stack = rot_around_x(input_stack); if axis[0]=='-': final_stack = StackProcessor(output_stack).rotateLeft(); else: final_stack = StackProcessor(output_stack).rotateRight(); out_imps.append(ImagePlus(title, final_stack)); new_cal.pixelWidth = original_cal.pixelDepth; new_cal.pixelDepth = original_cal.pixelWidth; elif axis=='z' or axis=='-z': for ch_imp in split_ch: if axis[0]=='-': output_stack = StackProcessor(ch_imp.getStack()).rotateLeft(); else: output_stack = StackProcessor(ch_imp.getStack()).rotateRight(); out_imps.append(ImagePlus(title, output_stack)); new_cal.pixelWidth = original_cal.pixelHeight; new_cal.pixelHeight = original_cal.pixelWidth; else: raise NotImplementedError("Please check which axis you've chosen - if not (x, +/-y, +/-z) then it's not implemented..."); imp.changes = False; imp.close(); if len(out_imps) > 1: out_imp = RGBStackMerge().mergeChannels(out_imps, False); else: out_imp = out_imps[0]; out_imp.setCalibration(new_cal); return out_imp;
def splitchannel(imp, chindex): nch = imp.getNChannels() print('Number of Channels: ' + str(nch)) # extract the channel if there are more than one if nch > 1: imps = ChannelSplitter.split(imp) imp = imps[chindex - 1] return imp
def makemontage(imp, hsize=5, vsize=5, increment=1): """Makes a montage of a multichannel ImagePlus object. Args: imp (ImagePlus): An ImagePlus object. hsize (int, optional): Size of the horizontal axis. Defaults to 5. vsize (int, optional): Size of the vertical axis. Defaults to 5. increment (int, optional): The increment between images. Allows for dropping of e.g. every second frame. Defaults to 1. Returns: ImagePlus: The montage as ImagePlus object. """ gridsize = hsize * vsize def _listProduct(inlist): """Calculates the product of all elements in a list. Args: inlist (list): A list of numbers. Returns: int or double: The product of all list elements. """ product = 1 for element in inlist: if isinstance(element, (int, float)): product = element * product return product def _channelmontage(_imp): """Makes a montage of a single channel ImagePlus object. Args: _imp (ImagePlus): A single channel ImagePlus object. Returns: ImagePlus: A montage of the one input channel. """ dims = _imp.getDimensions( ) # width, height, nChannels, nSlices, nFrames frames = _listProduct(dims[2:]) if frames > gridsize: frames = gridsize _montage = MontageMaker().makeMontage2(_imp, hsize, vsize, 1.00, 1, frames, increment, 0, True) return _montage name = imp.getTitle() channels = ChannelSplitter().split(imp) montages = [_channelmontage(channel) for channel in channels] montage = RGBStackMerge().mergeChannels(montages, False) montage.setTitle(name) return montage
def run(): srcDir = DirectoryChooser("Chose Source Dir").getDirectory() if srcDir is None: IJ.log("Choose Dir Canceled!") return outDir = DirectoryChooser("Chose >Output< Dir").getDirectory() if outDir is None: IJ.log("Output to same dir as source.") ourtDir = srcDir refImageId = getRefIdDialog() if refImageId is None: IJ.log("Select Reference Image Canceled!") return for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Skip non-ND2 files if not filename.endswith(".nd2"): continue inpath = os.path.join(root, filename) # outfn = "reg_" + os.path.splitext(filename)[0] + ".tif" # outpath = os.path.join(outDir, outfn) # if os.path.exists(outpath): # print "Skipped, already exists: ", outfn # continue IJ.log("Registering\n" + filename) imp = regBf(fn=inpath, refId=refImageId) if imp is None: IJ.log("Skipped, wrong with registration:\n" + filename) continue else: # fs = FileSaver(imp) # fs.saveAsTiffStack(outpath) # IJ.saveAsTiff(imp, outpath) # print "Registered and saved to ", outfn splittedimps = ChannelSplitter.split(imp) for i, simp in enumerate(splittedimps): outfn = "reg_" + os.path.splitext( filename)[0] + "_C_" + str(i) + ".tif" outpath = os.path.join(outDir, outfn) if os.path.exists(outpath): IJ.log("Skipped saving, file already exists:\n" + outfn) continue IJ.saveAsTiff(simp, outpath) IJ.log("Registered and saved to\n" + outfn) IJ.log("done!")
def run(): srcDir = DirectoryChooser("Chose Source Dir").getDirectory() if srcDir is None: IJ.log("Choose Dir Canceled!") return outDir = DirectoryChooser("Chose >Output< Dir").getDirectory() if outDir is None: IJ.log("Output to same dir as source.") ourtDir = srcDir refImageId = getRefIdDialog() if refImageId is None: IJ.log("Select Reference Image Canceled!") return for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Skip non-ND2 files if not filename.endswith(".nd2"): continue inpath = os.path.join(root, filename) # outfn = "reg_" + os.path.splitext(filename)[0] + ".tif" # outpath = os.path.join(outDir, outfn) # if os.path.exists(outpath): # print "Skipped, already exists: ", outfn # continue IJ.log("Registering\n" + filename) imp = regBf(fn=inpath, refId=refImageId) if imp is None: IJ.log("Skipped, wrong with registration:\n" + filename) continue else: # fs = FileSaver(imp) # fs.saveAsTiffStack(outpath) # IJ.saveAsTiff(imp, outpath) # print "Registered and saved to ", outfn splittedimps = ChannelSplitter.split(imp) for i, simp in enumerate(splittedimps): outfn = "reg_" + os.path.splitext(filename)[0] + "_C_" + str(i) + ".tif" outpath = os.path.join(outDir, outfn) if os.path.exists(outpath): IJ.log("Skipped saving, file already exists:\n" + outfn) continue IJ.saveAsTiff(simp, outpath) IJ.log("Registered and saved to\n" + outfn) IJ.log("done!")
def main(): files = [] for filt in img_extensions.split(";"): if len(filt.strip()) > 0: files += glob.glob(os.path.join(str(input_dir), filt.strip())) else: files += glob.glob(os.path.join(str(input_dir), "*.*")) break if len(files) == 0: IJ.showMessage("No files found in '{}'\nfor extensions '{}'".format( str(input_dir), img_extensions)) else: for fn in files: try: imp = BF.openImagePlus(fn)[0] except: IJ.showMessage( "Could not open file '{}' (skipping).\nUse extension filter to filter non-image files..." .format(str(fn))) continue img = IJF.wrap(imp) cali = imp.getCalibration().copy() if pixel_width > 0: cali.pixelWidth = pixel_width cali.pixelHeight = pixel_width cali.setUnit("micron") if frame_interval > 0: cali.frameInterval = frame_interval cali.setTimeUnit("sec.") imp_out = smooth_temporal_gradient(ops, img, sigma_xy, sigma_t, frame_start, frame_end, normalize_output) imp_out.setCalibration(cali) channels = ChannelSplitter.split(imp_out) fn_basename = os.path.splitext(fn)[0] IJ.save(channels[0], "{}_shrinkage.tiff".format(fn_basename)) IJ.save(channels[1], "{}_growth.tiff".format(fn_basename)) print("{} processed".format(fn_basename)) IJ.showMessage( "Growth/shrinkage extraction of {} inputs finsihed.".format( len(files)))
def main(): indir = IJ.getDirectory("input directory") outdir = IJ.getDirectory("output directory") files = sorted(os.listdir(indir)) # IJ.log("files: {}".format(files)) # montages = [] for imfile in files: IJ.log("File: {}/{}".format(files.index(imfile) + 1, len(files))) if imfile.endswith(".tif"): imp = Opener().openImage(indir, imfile) channels = ChannelSplitter().split(imp) name = outdir + imfile + "_t001_c001.tif" IJ.run(channels[0], "Image Sequence... ", "format=TIFF save={}".format(name))
def process(srcDir, dstDir, currentDir, fileName, keepDirectories): print "Processing:" # Opening the image print "Open image file", fileName imp = IJ.openImage(os.path.join(currentDir, fileName)) # Put your processing commands here! imps = ChannelSplitter.split(imp) impG = imps[1] # Saving the image saveDir = currentDir.replace(srcDir, dstDir) if keepDirectories else dstDir if not os.path.exists(saveDir): os.makedirs(saveDir) print "Saving to", saveDir savefilename = "Green_" + fileName IJ.saveAs(impG, "Tiff", os.path.join(saveDir, savefilename))
def preprocess(cell): print cell.getRawImageFilePath() imp = Opener().openImage(cell.getRawImageFilePath()) # open raw Image #if imp.getBitDepth() != 8: # converting to 8 bit if # ImageConverter(imp).convertToGray8() roi = imp.roi imps = CS.split(imp) p = Preprocessor() for aimp in imps: p.setImp(aimp) p.run() if roi != None: aimp.setRoi(roi) for n in range(1, aimp.getImageStackSize()+1): aimp.getImageStack().getProcessor(n).fillOutside(roi) aimp.killRoi() final = StackMerge.mergeChannels(imps, False) final.copyScale(imp) # copyscale from .copyscale return final
def shading_correction(infile, threshold): # Create artificial shading for stiching collection 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() current = ChannelSplitter.split(imp) for c in xrange(0, len(current)): results = [] for i in xrange(0, imp.getWidth()): roi = Line(0, i, imp.getWidth(), i) current[c].show() current[c].setRoi(roi) temp = IJ.run(current[c], "Reslice [/]...", "output=0.054 slice_count=1 rotate avoid") temp = IJ.getImage() ip = temp.getProcessor().convertToShort(True) pixels = ip.getPixels() w = ip.getWidth() h = ip.getHeight() row = [] for j in xrange(len(pixels)): row.append(pixels[j]) if j % w == w - 1: results.append(int(percentile(sorted(row), threshold))) row = [] reslice_names = "Reslice of C" + str(c + 1) + "-" + imp.getTitle() reslice_names = re.sub(".ids", "", reslice_names) IJ.selectWindow(reslice_names) IJ.run("Close") imp2 = IJ.createImage("shading_ch" + str(c + 1), "16-bit black", imp.getHeight(), imp.getWidth(), 1) pix = imp2.getProcessor().getPixels() for i in range(len(pix)): pix[i] = results[i] imp2.show() name = 'ch' + str(c + 1) + imp.getTitle() IJ.run(imp2, "Bio-Formats Exporter", "save=" + os.path.join(folder10, name)) IJ.selectWindow("shading_ch" + str(c + 1)) IJ.run('Close') IJ.selectWindow("C" + str(c + 1) + "-" + imp.getTitle()) IJ.run('Close')
def split_image_plus(imp, params): """split original ImagePlus by channel, and assign an image to segment on""" split_channels = ChannelSplitter.split(imp) membrane_channel_imp = split_channels[params.membrane_channel_number - 1] segmentation_channel_imp = Duplicator().run(membrane_channel_imp) if params.use_single_channel: actin_channel = params.membrane_channel_number actin_channel_imp = Duplicator().run(membrane_channel_imp) else: if imp.getNChannels() >= 2: actin_channel = (params.membrane_channel_number + 1) % imp.getNChannels() actin_channel_imp = split_channels[actin_channel - 1] else: actin_channel = params.membrane_channel_number actin_channel_imp = Duplicator().run(membrane_channel_imp) split_channels = [ membrane_channel_imp, actin_channel_imp, segmentation_channel_imp ] return split_channels
def manual_analysis(imp, file_name, output_folder): """perform analysis based on manually drawn cells""" cal = imp.getCalibration() channel_imps = ChannelSplitter.split(imp) gfp_imp = channel_imps[0] IJ.setTool("freehand") proceed = False roim = RoiManager() roim.runCommand("Show all with labels") dialog = NonBlockingGenericDialog("Perform manual segmentation") dialog.setOKLabel("Proceed to next image...") dialog.addMessage("Perform manual segmentation: ") dialog.addMessage( "Draw around cells and add to the region of interest manager (Ctrl+T)") dialog.addMessage( "You can see what you've added so far if you check \"show all\" on the ROI manager" ) dialog.addMessage( "Then press \"proceed to next image\" when all cells have been added") dialog.showDialog() if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled") elif dialog.wasOKed(): rois = roim.getRoisAsArray() roim.reset() roim.close() out_stats = generate_cell_shape_results(rois, gfp_imp, cal, file_name) print("Number of cells identified = {}".format(len(out_stats))) # save output save_qc_image( imp, rois, "{}_plus_overlay.tiff".format( os.path.join(output_folder, os.path.splitext(file_name)[0]))) save_cell_rois(rois, output_folder, os.path.splitext(file_name)[0]) imp.changes = False imp.close() save_output_csv(out_stats, output_folder) return out_stats return None
def split_and_rotate(imp, info): """return image to segment on, image to project out, and images to display""" # for now, assume that these are ISVs and that embryo is mounted in familiar fashion. First of these can be developed out... print("Image dimensions at start of split and rotate = ({}x{}x{}) pix". format(imp.getWidth(), imp.getHeight(), imp.getNSlices())) if imp.isVisible(): IJ.run("Enhance Contrast", "saturated=0.35") seg_ch_idx, proj_ch_idx = ui.choose_segmentation_and_projection_channels( info) channels = ChannelSplitter().split(imp) seg_imp = Duplicator().run(channels[seg_ch_idx]) # use Duplicator to decouple - can do smarter to save memory? proj_imp = Duplicator().run(channels[proj_ch_idx]) rot_seg_imp = utils.rot3d(seg_imp, axis='x') rot_seg_imp.setTitle("rot_seg_imp") rot_proj_imp = utils.rot3d(proj_imp, axis='x') rot_proj_imp.setTitle("rot_proj_imp") egfp_mch_imps = [] egfp_idx = 0 if "gfp" in info.ch1_label.lower() else 1 mch_idx = int(not (egfp_idx)) # assume two channel... for ch_idx in [egfp_idx, mch_idx]: if ch_idx == seg_ch_idx: egfp_mch_imps.append(Duplicator().run(rot_seg_imp)) elif ch_idx == proj_ch_idx: egfp_mch_imps.append(Duplicator().run(rot_proj_imp)) else: egfp_mch_imps.append( utils.rot3d(Duplicator().run(channels[ch_idx]), axis='x')) imp.changes = False imp.close() seg_imp.changes = False proj_imp.changes = False seg_imp.close() proj_imp.close() print("Image dimensions at start of split and rotate = ({}x{}x{}) pix". format(rot_proj_imp.getWidth(), rot_proj_imp.getHeight(), rot_proj_imp.getNSlices())) return rot_seg_imp, rot_proj_imp, egfp_mch_imps
def convertAndSaveFile(fullFilePath, convertTo8Bit=False, allowOverwrite=False): """ """ print(' convertAndSaveFile() fullFilePath:', fullFilePath) folderPath, fileName = os.path.split(fullFilePath) fileNameNoExtension = os.path.splitext(fileName)[0] saveFileNoExtension = os.path.join(folderPath, fileNameNoExtension) # # load file and build a dict of parameters like (channels, pixels, voxels) myFileInfo, imp = bSimpleFileInfo.myLoadFile(fullFilePath, doShow=True) if convertTo8Bit: # from (ImagePlus.GRAY8, ImagePlus.GRAY16, ImagePlus.GRAY32, ImagePlus.COLOR_256 or ImagePlus.COLOR_RGB) myType = imp.getType() if myType in [1,2]: ic = ImageConverter(imp) # converts channelImp in place scaleConversions = True ic.setDoScaling(scaleConversions) # scales inensities to fill 0...255 ic.convertToGray8() # # split channels channelArray = ChannelSplitter.split(imp) # returns an array of imp for channelIdx, channelImp in enumerate(channelArray): # channelImp is an imp, this will NOT have fileinfo (we just created it) #channelImp.show() saveFilePath = saveFileNoExtension + '_ch' + str(channelIdx+1) + '.tif' print(' ch:', channelIdx+1, 'saveFilePath:', saveFilePath) if not allowOverwrite and os.path.isfile(saveFilePath): print(' . not saving, file already exists', saveFilePath) else: IJ.save(channelImp, saveFilePath) return myFileInfo
def split_by_c_and_z(log, dname, imgf, skip_top, skip_bottom): """Helper function to open, split and save a file. Load the file specified, split by channels and z-slices, create a directory for each channel using the channel number as a name suffix and export each slice as an individual TIF file. Parameters ---------- log : logger or scijava-logservice The logger object to be used for logging. dname : str The directory to load TIF files from. imgf : str The file name to load and split. skip_top : int Number of slices to skip at the top. skip_bottom : int Number of slices to skip at the bottom. """ log.info("Processing file [%s]" % imgf) imp = IJ.openImage(dname + "/" + imgf) fname = os.path.splitext(imgf) channels = ChannelSplitter().split(imp) for channel in channels: c_name = channel.getTitle().split("-")[0] tgt_dir = os.path.join(dname, fname[0] + "-" + c_name) if not os.path.isdir(tgt_dir): os.mkdir(tgt_dir) stack = channel.getStack() for z in range(1 + skip_top, stack.getSize() + 1 - skip_bottom): proc = stack.getProcessor(z) fout = "%s/%s-z%s%s" % (tgt_dir, fname[0], z, fname[1]) # fout = dname + "/" + c_name + "/" + fname[0] + "-z" + z + fname[1] log.info("Writing channel %s, slice %s: %s" % (c_name, z, fout)) FileSaver(ImagePlus(fname[0], proc)).saveAsTiff(fout)
rm = RoiManager() rm.reset() # Process images for impfile in file_list: # open image imp = IJ.openImage(os.path.join(input_folder, impfile)) imp.show() impname = impfile.strip('.tif') imp_details = impname.split('_') stain, mutant, pos_number = imp_details print mutant, stain, pos_number imps = ChannelSplitter.split(imp) # Process cell ROIs rm = cell_processor(imp_particles=imps[3], imp_measure=imps[2], folder=folder, impname=impname, channel_name='GFP_cells') pixel_collector(rm, imps[3], 'cyto_mCherry_cells', impname, folder) pixel_collector(rm, imps[4], 'inc_mCherry_cells', impname, folder) rm.reset() ## Process nuclei image imps_thresh = ChannelSplitter.split(imp) nuclei_processor(imp_particles=imps_thresh[0], thresh_type='Otsu dark',
outDir = DirectoryChooser("Batch Splitter: Chose >Output< Dir").getDirectory() if outDir is None: print "Output to same dir as source." ourtDir = srcDir for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Skip non-TIF files if not filename.endswith(".tif"): continue inpath = os.path.join(root, filename) print "Reading ", filename imp = IJ.openImage(inpath) if imp is None: print "Skipped, wrong with reading: ", filename continue else: splittedimps = ChannelSplitter.split(imp) for i, simp in enumerate(splittedimps): outfn = os.path.splitext(filename)[0] + "_C_" + str(i) + ".tif" outpath = os.path.join(outDir, outfn) if os.path.exists(outpath): print "Skipped, already exists: ", outfn continue IJ.saveAsTiff(simp, outpath) print "Splitted and saved to ", outfn print "done."
def track(): imp = IJ.getImage() nChannels = imp.getNChannels() # Get the number of channels orgtitle = imp.getTitle() IJ.run("Subtract Background...", "rolling=50 sliding stack") IJ.run("Enhance Contrast...", "saturated=0.3") IJ.run("Multiply...", "value=10 stack") IJ.run("Subtract Background...", "rolling=50 sliding stack") IJ.run("Set Scale...", "distance=0") channels = ChannelSplitter.split(imp) imp_GFP = channels[0] imp_RFP = channels[1] IJ.selectWindow(orgtitle) IJ.run("Close") ic = ImageCalculator() imp_merge = ic.run("Add create stack", imp_GFP, imp_RFP) imp_merge.setTitle("add_channels") imp_merge.show() imp_RFP.show() imp_GFP.show() imp5 = ImagePlus() IJ.run(imp5, "Merge Channels...", "c1=[" + imp_merge.title + "] c2=" + imp_GFP.title + ' c3=' + imp_RFP.title + " create") print("c1=[" + imp_merge.title + "] c2=" + imp_GFP.title + ' c3=' + imp_RFP.title + " create") imp5.show() imp5 = IJ.getImage() nChannels = imp5.getNChannels() # Setup settings for TrackMate settings = Settings() settings.setFrom(imp5) # Spot analyzer: we want the multi-C intensity analyzer. settings.addSpotAnalyzerFactory(SpotMultiChannelIntensityAnalyzerFactory()) # Spot detector. settings.detectorFactory = LogDetectorFactory() settings.detectorSettings = settings.detectorFactory.getDefaultSettings() settings.detectorSettings['TARGET_CHANNEL'] = 1 settings.detectorSettings['RADIUS'] = 24.0 settings.detectorSettings['THRESHOLD'] = 0.0 # Spot tracker. # Configure tracker - We don't want to allow merges or splits settings.trackerFactory = SparseLAPTrackerFactory() settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap() # almost good enough settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = False settings.trackerSettings['ALLOW_TRACK_MERGING'] = False settings.trackerSettings['LINKING_MAX_DISTANCE'] = 8.0 settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = 8.0 settings.trackerSettings['MAX_FRAME_GAP'] = 1 # Configure track filters settings.addTrackAnalyzer(TrackDurationAnalyzer()) settings.addTrackAnalyzer(TrackSpotQualityFeatureAnalyzer()) filter1 = FeatureFilter('TRACK_DURATION', 20, True) settings.addTrackFilter(filter1) # Run TrackMate and store data into Model. model = Model() trackmate = TrackMate(model, settings) ok = trackmate.checkInput() if not ok: sys.exit(str(trackmate.getErrorMessage())) ok = trackmate.process() if not ok: sys.exit(str(trackmate.getErrorMessage())) selectionModel = SelectionModel(model) displayer = HyperStackDisplayer(model, selectionModel, imp5) displayer.render() displayer.refresh() IJ.log('TrackMate completed successfully.') IJ.log('Found %d spots in %d tracks.' % (model.getSpots().getNSpots(True) , model.getTrackModel().nTracks(True))) # Print results in the console. headerStr = '%10s %10s %10s %10s %10s %10s' % ('Spot_ID', 'Track_ID', 'Frame', 'X', 'Y', 'Z') rowStr = '%10d %10d %10d %10.1f %10.1f %10.1f' for i in range( nChannels ): headerStr += (' %10s' % ( 'C' + str(i+1) ) ) rowStr += ( ' %10.1f' ) #open a file to save results myfile = open('/home/rickettsia/Desktop/data/Clamydial_Image_Analysis/EMS_BMECBMELVA_20X_01122019/data/'+orgtitle.split('.')[0]+'.csv', 'wb') wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(['Spot_ID', 'Track_ID', 'Frame', 'X', 'Y', 'Z', 'Channel_1', 'Channel_2']) IJ.log('\n') IJ.log(headerStr) tm = model.getTrackModel() trackIDs = tm.trackIDs(True) for trackID in trackIDs: spots = tm.trackSpots(trackID) # Let's sort them by frame. ls = ArrayList(spots) for spot in ls: values = [spot.ID(), trackID, spot.getFeature('FRAME'), \ spot.getFeature('POSITION_X'), spot.getFeature('POSITION_Y'), spot.getFeature('POSITION_Z')] for i in range(nChannels): values.append(spot.getFeature('MEAN_INTENSITY%02d' % (i+1))) IJ.log(rowStr % tuple(values)) l1 = (values[0], values[1], values[2], values[3], values[4], values[5], values[7], values[8]) wr.writerow(l1) myfile.close() IJ.selectWindow("Merged") IJ.run("Close")
def splitChannels(orgimp): imps = ChannelSplitter.split(orgimp) return imps[1], imps[2]
tubimg = ImagePlus("img", tubimg) result[index] = tubimg # vessel detection training dc = DirectoryChooser("Choose a folder") folder = dc.getDirectory() pos = IJ.openImage(folder + "\\vessels_positive.tif") posroi = pos.getRoi() neg = IJ.openImage(folder + "\\vessels_negative.tif") negroi = neg.getRoi() pos.close() IJ.run("Select None", "") channels = ChannelSplitter.split(neg) neg.close() image = channels[3] channels = channels[0:3] proc = image.getProcessor() directional_op = ImagePlus("directional_op", proc) IJ.run(directional_op, "Directional Filtering", "type=Max operation=Opening line=30 direction=32") directional_op = WindowManager.getImage("directional_op-directional") tubes = range(5, 130, 12) img_source = ImagePlus("image", proc) src = clij2.push(img_source)
for fileName in listdir(path): if regEx.match(fileName): # if matches RE, add to list moFileList.append(regEx.match(fileName)) if moFileList == []: IJ.showMessage("Input Exception", "No unprocessed images found in the directory you selected.") raise IOError("No unpocessed TIFFs found in this folder.") for image in moFileList: print "Processing cell " + image.group() + " (" + str(moFileList.index(image)+1) + "/" + str(len(moFileList)) + ")" IJ.log("Processing cell " + image.group() + " (" + str(moFileList.index(image)+1) + "/" + str(len(moFileList)) + ")") imp = Opener().openImage(path + image.group()) # open Image #if imp.getBitDepth() != 8: # converting to 8 bit if # ImageConverter(imp).convertToGray8() roi = imp.roi imps = CS.split(imp) ppc = PPC() for aimp in imps: ppc.setImp(aimp) ppc.run() if roi != None: aimp.setRoi(roi) for n in range(1, aimp.getImageStackSize()+1): aimp.getImageStack().getProcessor(n).fillOutside(roi) aimp.killRoi() final = StackMerge.mergeChannels(imps, False) final.copyScale(imp) # copyscale from .copyscale if not pth.exists(saveFolder): makedirs(saveFolder) fileName = G_saveFilePrefix + image.group('prefix') IJ.saveAs(final, ".tiff", pth.join(saveFolder, fileName) ) # saveAs(ImagePlus imp, java.lang.String format, java.lang.String path)
manders = MandersColocalization() results = ResultsTable() for imageFile in os.listdir(inputDir): print "Opening " + imageFile try: images = BF.openImagePlus(inputDir + imageFile) image = images[0] except UnknownFormatException: continue preview = getPreview(image) preview.show() rm = RoiManager() dialog = WaitForUserDialog("Action required", "Please select regions of interest in this image. Click OK when done.") dialog.show() rm.close() splitter = ChannelSplitter() imp1 = ImagePlus("CH1", splitter.getChannel(image, imageA)) imp2 = ImagePlus("CH2", splitter.getChannel(image, imageB)) title = image.getTitle() title = title[:title.rfind('.')] image.close() preview.close() ch1 = ImagePlusAdapter.wrap(imp1) ch2 = ImagePlusAdapter.wrap(imp2) for roi in rm.getRoisAsArray(): container = createContainer(roi, ch1, ch2) img1 = container.getSourceImage1() img2 = container.getSourceImage2() mask = container.getMask()
activeImage.copyScale(calibImage) calib = calibImage.getCalibration() calibImage.close() activeImage.updateAndRepaintWindow() else: calib = activeImage.getCalibration() ## Runs interface that allows to correct for bleedthrough and refraction if activeImage is not None: gd = NonBlockingGenericDialog("Select channel to operate on...") gd.addChoice("Select_channel:",["Channel "+str(i) for i in range(1,activeImage.getNChannels()+1)],"Channel 1") gd.addChoice("Bleeding_channel:",["None"] + ["Channel "+str(i) for i in range(1,activeImage.getNChannels()+1)],"None") gd.addChoice("Refraction_reference_channel:",["None"] + ["Channel "+str(i) for i in range(1,activeImage.getNChannels()+1)],"None") gd.showDialog() if (gd.wasOKed()): channelImages = ChannelSplitter.split(activeImage) channel = gd.getNextChoiceIndex()+1 bleedingC = gd.getNextChoiceIndex() refractRefC = gd.getNextChoiceIndex() if (bleedingC > 0): params = ("bleeding_channel=" + str(bleedingC) + " bloodied_channel=" + str(channel) + " " + "allowable_saturation_percent=1.0 rsquare_threshold=0.50") IJ.run("Remove Bleedthrough (automatic)", params) dataImage = WindowManager.getImage("Corrected_ch" + str(channel)) if (refractRefC > 0): refractCImage = channelImages[refractRefC-1].duplicate() refractCImage.show() IJ.run("Merge Channels...", "c1=" + dataImage.getTitle() + " c2=" + refractCImage.getTitle() + " create ignore") mergedImage = WindowManager.getImage("Composite") params = ("reference_channel=2 application_channel=1 automatic_operation generate_log " + "max_slice=43 surface_slice=87")
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters): title = inputImp.getTitle() title=title.replace('UV', 'SD') print title #trueColorImp= WindowManager.getImage(title) #print type( trueColorImp) # calculate are of roi stats=inputImp.getStatistics() inputRoiArea=stats.area print inputRoi # get the bounding box of the active roi inputRec = inputRoi.getBounds() x1=long(inputRec.getX()) y1=long(inputRec.getY()) x2=x1+long(inputRec.getWidth())-1 y2=y1+long(inputRec.getHeight())-1 print x1 print y1 print x2 print y2 # crop the roi interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') ) cropped=ops.crop(interval, None, inputDataset.getImgPlus() ) datacropped=data.create(cropped) display.createDisplay("cropped", datacropped) croppedPlus=IJ.getImage() duplicator=Duplicator() substackMaker=SubstackMaker() # duplicate the roi duplicate=duplicator.run(croppedPlus) #duplicate.show() # convert duplicate of roi to HSB and get brightness IJ.run(duplicate, "HSB Stack", ""); brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3") brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus)) brightnessPlus.setTitle("Brightness") #brightnessPlus.show() # make another duplicate, split channels and get red duplicate=duplicator.run(croppedPlus) channels=ChannelSplitter().split(duplicate) redPlus=channels[0] red=ImgPlus(ImageJFunctions.wrapByte(redPlus)) redPlus.show() # convert to lab IJ.run(croppedPlus, "Color Transformer", "colour=Lab") IJ.selectWindow('Lab') labPlus=IJ.getImage() # get the A channel APlus=substackMaker.makeSubstack(labPlus, "2-2") APlus.setTitle('A') APlus.show() APlus.getProcessor().resetMinAndMax() APlus.updateAndDraw() AThresholded=threshold(APlus, -10, 50) # get the B channel BPlus=substackMaker.makeSubstack(labPlus, "3-3") BPlus.setTitle('B') BPlus.show() BPlus.getProcessor().resetMinAndMax() BPlus.updateAndDraw() BThresholded=threshold(BPlus, -10, 50) # AND the Athreshold and Bthreshold to get a map of the red pixels ic = ImageCalculator(); redMask = ic.run("AND create", AThresholded, BThresholded); IJ.run(redMask, "Divide...", "value=255"); #redMask.show() labPlus.close() # threshold the spots from the red channel thresholdedred=SpotDetectionGray(red, data, display, ops, False) display.createDisplay("thresholdedred", data.create(thresholdedred)) impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped") # threshold the spots from the brightness channel thresholded=SpotDetectionGray(brightness, data, display, ops, False) display.createDisplay("thresholded", data.create(thresholded)) impthresholded=ImageJFunctions.wrap(thresholded, "wrapped") # or the thresholding results from red and brightness channel impthresholded = ic.run("OR create", impthresholded, impthresholdedred); # convert to mask Prefs.blackBackground = True IJ.run(impthresholded, "Convert to Mask", "") # clear the region outside the roi clone=inputRoi.clone() clone.setLocation(0,0) Utility.clearOutsideRoi(impthresholded, clone) # create a hidden roi manager roim = RoiManager(True) # count the particlesimp.getProcessor().setColor(Color.green) countParticles(impthresholded, roim, detectionParameters.minSize, detectionParameters.maxSize, detectionParameters.minCircularity, detectionParameters.maxCircularity) # define a function to determine the percentage of pixels that are foreground in a binary image # inputs: # imp: binary image, 0=background, 1=foreground # roi: an roi def isRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.redPercentage): return True else: return False def notRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.redPercentage): return False else: return True allList=[] for roi in roim.getRoisAsArray(): allList.append(roi.clone()) # count particles that are red redList=CountParticles.filterParticlesWithFunction(redMask, allList, isRed) # count particles that are red blueList=CountParticles.filterParticlesWithFunction(redMask, allList, notRed) print "Total particles: "+str(len(allList)) print "Filtered particles: "+str(len(redList)) # for each roi add the offset such that the roi is positioned in the correct location for the # original image [roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in allList] # create an overlay and add the rois overlay1=Overlay() inputRoi.setStrokeColor(Color.green) overlay1.add(inputRoi) [CountParticles.addParticleToOverlay(roi, overlay1, Color.red) for roi in redList] [CountParticles.addParticleToOverlay(roi, overlay1, Color.cyan) for roi in blueList] def drawAllRoisOnImage(imp, mainRoi, redList, blueList): imp.getProcessor().setColor(Color.green) IJ.run(imp, "Line Width...", "line=3"); imp.getProcessor().draw(inputRoi) imp.updateAndDraw() IJ.run(imp, "Line Width...", "line=1"); [CountParticles.drawParticleOnImage(imp, roi, Color.magenta) for roi in redList] [CountParticles.drawParticleOnImage(imp, roi, Color.green) for roi in blueList] imp.updateAndDraw() drawAllRoisOnImage(inputImp, inputRoi, redList, blueList) #drawAllRoisOnImage(trueColorImp, inputRoi, redList, blueList) # draw overlay #inputImp.setOverlay(overlay1) #inputImp.updateAndDraw() statsdict=CountParticles.calculateParticleStats(APlus, BPlus, redMask, roim.getRoisAsArray()) print inputRoiArea areas=statsdict['Areas'] poreArea=0 for area in areas: poreArea=poreArea+area ATotal=0 ALevels=statsdict['ALevel'] for A in ALevels: ATotal=ATotal+A AAverage=ATotal/len(ALevels) BTotal=0 BLevels=statsdict['BLevel'] for B in BLevels: BTotal=BTotal+B BAverage=BTotal/len(BLevels) redTotal=0 redPercentages=statsdict['redPercentage'] for red in redPercentages: redTotal=redTotal+red redAverage=redTotal/len(redPercentages) pixwidth=inputImp.getCalibration().pixelWidth inputRoiArea=inputRoiArea/(pixwidth*pixwidth) print str(len(allList))+" "+str(len(redList))+" "+str(len(blueList))+" "+str(poreArea/inputRoiArea)+" "+str(redAverage)
script_path = os.getcwd() if "Fiji.app" in script_path: ss = script_path.split("Fiji.app") final_folder = "marcksl1 shape prescreener" script_path = os.path.join(ss[0], "Fiji.app", "plugins", "Scripts", "Plugins", final_folder) sys.path.insert(0, os.path.join(script_path, 'modules')) sys.path.insert(0, os.path.join(script_path, 'classes')) from UpdateRoiImageListener import UpdateRoiImageListener # angle method max_r_pix = 60 min_r_pix = 10 split_chs = ChannelSplitter().split(imp) mch_imp = split_chs[0] egfp_imp = split_chs[1] egfp_imp_disp = Duplicator().run(egfp_imp) cl_imp = split_chs[2] #egfp_imp.show(); centres = [] projected_im_pix = [] ring_rois = [] unzip_axis = [] roi_stack = IJ.createImage("rois", egfp_imp.getWidth(), egfp_imp.getHeight(), egfp_imp.getNSlices(), 16) #roi_stack.show(); for zidx in range(cl_imp.getNSlices()):
# Check if folders are there or not if not os.path.exists(saveDir): os.mkdir(saveDir) # set up options for import opts = ImporterOptions() opts.setId(filename) opts.setUngroupFiles(True) # set up import process process = ImportProcess(opts) process.execute() nseries = process.getSeriesCount() # Channel Splitter Definition splitter = ChannelSplitter() # reader belonging to the import process reader = process.getReader() # reader external to the import process impReader = ImagePlusReader(process) # loop through all series in file for i in range(0, nseries): print "%d/%d %s" % (i+1, nseries, process.getSeriesLabel(i)[10:]) # activate series (same as checkbox in GUI) opts.setSeriesOn(i,True) # point import process reader to this series
testTile = WindowManager.getImage(windowName) numTotalChannels = testTile.getNChannels() labels = ["" for x in range(numTotalChannels)] defaultValues = [False for x in range(numTotalChannels)] for i in range(1,numTotalChannels+1): labels[i-1] = "Channel" + str(i) defaultValues[i-1] = False ## Allows user to choose which channels to analyze gd = NonBlockingGenericDialog("Select channel...") gd.addCheckboxGroup(numTotalChannels,1,labels,defaultValues) gd.showDialog() runOnChannel = [False for x in range(numTotalChannels)] for i in range(numTotalChannels): runOnChannel[i] = gd.getNextBoolean() ## Runs the 3D object counter on all the tiles and saves the results to disk IJ.run("3D OC Options", "volume surface nb_of_obj._voxels nb_of_surf._voxels integrated_density mean_gray_value std_dev_gray_value median_gray_value minimum_gray_value maximum_gray_value centroid mean_distance_to_surface std_dev_distance_to_surface median_distance_to_surface centre_of_mass bounding_box dots_size=5 font_size=10 show_numbers white_numbers store_results_within_a_table_named_after_the_image_(macro_friendly) redirect_to=none"); channelImage = ChannelSplitter.split(testTile) testTile.close() for i in range(numTotalChannels): if (runOnChannel[i]): channelImage[i].show() IJ.run(channelImage[i], "3D Objects Counter", "threshold=42 slice=47 min.=300 max.=24903680 statistics") IJ.saveAs("Results", "/Volumes/DUNCAN/2015/03_12_15 ERT2 Confetti DSS earlier trace/A5/9396-abluminal.lsm_tiles/objects/C" + str(i+1) + "-tile_45.csv") channelImage[i].close() resultsWindows = WindowManager.getAllNonImageWindows() for i in range(len(resultsWindows)): resultsWindows[i].dispose()
subfolders = [""] for subfolder in subfolders: #Opens each image for filename in os.listdir(inputDirectory + subfolder): imp = IJ.openImage(inputDirectory + subfolder + '/' + filename) if imp: #IJ.run(imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.87" "pixel_height=0.87" "voxel_depth=25400.0508001") # Splits channels channels = ChannelSplitter.split(imp); # Measures each channel #Summary contains the information for a row for the current image summary = {} summary['Directory'] = inputDirectory + subfolder summary['Filename'] = filename #Color keeps the names for each channel color = ["Red", "Green", "Blue"] for i, channel in enumerate(channels):
def run(): zk = ZeissKeys() msg = Message() timestart = time.clock() channel = 1 #size in um2 minArea = 20 maxArea = 200 maxMetaArea = 70 minMetaAR = 1.8 method = "Triangle" print "Enter run" detectionNucleus = [minArea, maxArea] detectionMetaphase = [minArea, maxMetaArea] filepath = "" try: filepath = getArgument() image = IJ.openImage(filepath) #arguments provided by runMacro except NameError: try: filepath = newImagePath #argument provided by the macroRunner except NameError: #no file name specified errMsg = "Fiji error segmentNuclei.py: no filepath has been passed to the macro" exitWithError(errMsg) od = OpenDialog("Choose image file", None) if od.getFileName() == None: return filepath = os.path.join(od.getDirectory(), od.getFileName()) # A roimanager is recquired roim = RoiManager.getInstance() if roim == None: roim = RoiManager() #test a last time if roim == None: print 'Fiji error segmentNuclei.py: no RoiManager!' exitWithError('Fiji error segmentNuclei.py: no RoiManager!') try: IJ.run("Close all forced") IJ.run("Clear Results") IJ.log("\\Clear") image = IJ.openImage(filepath) IJ.log("File Path " + filepath) try: image.hide() except: image = IJ.getImage() image.hide() image.show() if image is None: exitWithError("Fiji failed to open image") return 0 #convert um2 to pixels pixelSize = image.getCalibration().pixelWidth detectionNucleus = [area/pixelSize/pixelSize for area in detectionNucleus] detectionMetaphase = [area/pixelSize/pixelSize for area in detectionMetaphase] detectionMetaphase.append(minMetaAR) title = image.getTitle() imageC = None #split colors if needed if image.getNChannels() > 1: chSp = ChannelSplitter() imageC = chSp.split(image) imageSeg = imageC[channel-1].duplicate() else: imageSeg = image.duplicate() imageSeg.setTitle("SEG_"+title) sp = segment_Particles() imageSeg = sp.preprocessImage(imageSeg, "MAX", "C1", 2, 2) imageSeg = sp.segmentParticles(imageSeg, method, detectionNucleus[0], detectionNucleus[1], 2, 2) roim = RoiManager.getInstance() if roim == None: print 'Fiji error segmentNuclei.py: no RoiManager!' exitWithError('Fiji error segmentNuclei.py: no RoiManager!') #compute central object if roim.getCount() > 0: centPart, msg.position = centerParticle(imageSeg, roim) msg.position = msg.position + (focusParticle(image, roim, centPart),) writePositionToRegistry(msg.position) else: IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_NOTHING+"] windows=REG_SZ") return 0 #create output image if imageC is None: impOut = createOutputImg(image, roim, centPart, 0) else: impOut = createOutputImg(imageC[channel-1], roim, centPart, 0) impOut.show() #save outut image #saveOutputImg(impOut, filepath, 'Analyzed') #check for roi properties to identofy metaphase metaphase = isSpecialParticle(image, roim, centPart,detectionNucleus, detectionMetaphase,pixelSize, msg.position[2]) if os.path.basename(filepath).startswith('TR1_') or '_TR1_' in os.path.basename(filepath): metaphase = 0 if metaphase: IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_TRIGGER1+"] windows=REG_SZ") else: IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_FOCUS+"] windows=REG_SZ") IJ.log("time focus " + str(time.clock() - timestart)) IJ.run("Collect Garbage") #IJ.run("Close all forced") #IJ.run("Clear Results") except BaseException, err:
def straighten_vessel(imp, smooth_centres, it=1, save_output=False): """use IJ straigtening tool to deal with convoluted vessels""" print("straighten vessel input image dims = " + str(imp.getWidth()) + "x" + str(imp.getHeight())) rot_imp = utils.rot3d(imp, axis='x') if it == 1: roi = PolygonRoi([x for x, y, z in smooth_centres], [z for x, y, z in smooth_centres], Roi.FREELINE) print("len interp polygon = " + str(roi.getInterpolatedPolygon().npoints)) elif it == 2: new_zs = [z for z in range(rot_imp.getWidth())] new_ys = lin_interp_1d([z for x, y, z in smooth_centres], [y for x, y, z in smooth_centres], new_zs) roi = PolygonRoi(new_zs, new_ys, Roi.FREELINE) split_ch = ChannelSplitter().split(rot_imp) mch_imp = split_ch[0] egfp_imp = split_ch[1] roi_imp = split_ch[2] roi_imp.setRoi(roi) for zidx in range(egfp_imp.getNSlices()): for chidx in range(3): split_ch[chidx].setZ(zidx + 1) split_ch[chidx].setRoi(roi) ip = Straightener().straightenLine(split_ch[chidx], 150) if chidx == 1: if zidx == 0: egfp_straight_stack = ImageStack(ip.getWidth(), ip.getHeight()) egfp_straight_stack.addSlice(ip) elif chidx == 0: if zidx == 0: mch_straight_stack = ImageStack(ip.getWidth(), ip.getHeight()) mch_straight_stack.addSlice(ip) else: if zidx == 0: roi_straight_stack = ImageStack(ip.getWidth(), ip.getHeight()) roi_straight_stack.addSlice(ip) egfp_out_imp = ImagePlus("Straightened EGFP", egfp_straight_stack) mch_out_imp = ImagePlus("Straightened mCh", mch_straight_stack) roi_out_imp = ImagePlus("Straightened ROI", roi_straight_stack) if it == 2: egfp_out_imp = utils.rot3d(egfp_out_imp, axis='y') mch_out_imp = utils.rot3d(mch_out_imp, axis='y') roi_out_imp = utils.rot3d(roi_out_imp, axis='y') egfp_out_imp.show() mch_out_imp.show() roi_out_imp.show() IJ.run( "Merge Channels...", "c1=[" + mch_out_imp.getTitle() + "] c2=[" + egfp_out_imp.getTitle() + "] c7=[" + roi_out_imp.getTitle() + "] create keep") # WaitForUserDialog("pause").show(); # if it==1: egfp_out_imp.close() mch_out_imp.close() roi_out_imp.close() new_composite = IJ.getImage() if save_output: FileSaver(new_composite).saveAsTiffStack( os.path.join(output_path, "after rotation " + str(it) + ".tif")) return new_composite
raise IOError("Input Exception: Directory does not contain any preprocessed images.") if not pth.exists(saveFolder): # check if directory for analysis-files is present makedirs(saveFolder) for image in moFileList: # get rid of 0! print "starting with cell " + image.group() + " " + "("+ str(moFileList.index(image)) + "/" + str(len(moFileList)) + ")" imp = Opener().openImage(inputDir + image.group()) # open Image # read calibration for later calculation of distances in um. calibration = imp.getCalibration() pxWidth = calibration.pixelWidth print "px depth", calibration.pixelDepth timeInterval = round(calibration.frameInterval) #start measurement splitCh = CS.split(imp) # split channels #try: ATA().segAndMeasure(splitCh[0], splitCh[1]) # perform segmentation and measurement #else: go to next element in moFileList # move image to "segProblem" folder # continue WindowManager.getImage("binProjMerged").close() WindowManager.getImage("DUP_C1-"+image.group()).close() WindowManager.getImage("DUP_C2-"+image.group()).close() # read the measurements from results tables. distance_lines = WindowManager.getFrame("Statistics_Distance").getTextPanel().getText().split("\n") ch0_dots = tableToDots(WindowManager.getFrame("Statistics_Ch0").getTextPanel().getText().split("\n"), 0) ch1_dots = tableToDots(WindowManager.getFrame("Statistics_Ch1").getTextPanel().getText().split("\n"), 1)
theImage = IJ.getImage() gd = GenericDialog("Options...") channelText = [("Channel " + str(ch+1)) for ch in range(theImage.getNChannels())] gd.addChoice("Amplified_channel",channelText,channelText[0]) gd.addChoice("Reference_channel",channelText,channelText[-1]) gd.addNumericField("Amplifying_ratio",1,0) gd.addCheckbox("Remove_bleedthrough",True) gd.addCheckbox("Correct_for_refraction",True) gd.showDialog() if gd.wasOKed(): amplifyChannel = gd.getNextChoiceIndex() + 1 refChannel = gd.getNextChoiceIndex() + 1 ampFactor = gd.getNextNumber() doRemoveBleedthrough = gd.getNextBoolean() doCorrectRefraction = gd.getNextBoolean() chImages = ChannelSplitter.split(theImage) ## After this step, the image to operate on is "nextStepImage" if doRemoveBleedthrough: params = ("bleeding_channel=" + str(refChannel) + " bloodied_channel=" + str(amplifyChannel) + " " + "allowable_saturation_percent=1.0 rsquare_threshold=0.50") IJ.run("Remove Bleedthrough (automatic)", params) unbledImage = WindowManager.getImage("Corrected_ch" + str(amplifyChannel)) mergingImages = [unbledImage,chImages[refChannel-1].duplicate()] nextStepImage = RGBStackMerge.mergeChannels(mergingImages,True) #nextStepImage.show() unbledImage.close() for img in mergingImages: img.close() else: mergingImages = [chImages[amplifyChannel-1].duplicate(),chImages[refChannel-1].duplicate()]
from ij.measure import ResultsTable from ij.measure import Measurements from ij.plugin.filter import Analyzer ## Main body of script theImage = IJ.getImage() gd = NonBlockingGenericDialog("Pick parameters...") gd.addChoice("Analysis_channel",["Channel "+str(i+1) for i in range(theImage.getNChannels())],"Channel 1") gd.addNumericField("Pick_threshold",50,0) gd.addCheckbox("Apply_min",True) gd.showDialog() if (gd.wasOKed()): analysisChannel = gd.getNextChoiceIndex() + 1 intensityThreshold = gd.getNextNumber() doMin = gd.getNextBoolean() splitImage = ChannelSplitter.split(theImage) dataImage = splitImage[analysisChannel-1].duplicate() if doMin: IJ.run(dataImage,"Minimum...", "radius=2 stack") goRun = True rt = ResultsTable() while goRun: wfud = WaitForUserDialog("Pick freehand ROI, then hit OK to analyze") wfud.show() roi = theImage.getRoi() if roi is None: goRun = False else: dataImage.setRoi(roi) subImage = dataImage.duplicate() dataIp = dataImage.getProcessor()
print tileList except: IJ.log("Problem parsing your tile subset!") parsingFailed = True else: tileList = range(1,nTiles+1) ## Applies corrections to individual tiles, then runs the object counter if not parsingFailed: for tile in tileList: params = ("open=["+ parentLSMFilePath + "_tiles/tile_" + str(tile) + ".ome.tif] " + "color_mode=Default view=Hyperstack stack_order=XYCZT") IJ.run("Bio-Formats Importer", params) theImage = WindowManager.getImage("tile_" + str(tile) + ".ome.tif") calibration = theImage.getCalibration() channelImages = ChannelSplitter.split(theImage) if (bleedingChannel > 0): params = ("bleeding_channel=" + str(bleedingChannel) + " bloodied_channel=" + str(analysisChannel) + " " + "allowable_saturation_percent=1.0 rsquare_threshold=0.50") IJ.run("Remove Bleedthrough (automatic)", params) dataImage = WindowManager.getImage("Corrected_ch" + str(analysisChannel)) if (refChannel > 0): refractCImage = channelImages[refChannel-1].duplicate() refractCImage.show() IJ.run("Merge Channels...", "c1=" + dataImage.getTitle() + " c2=" + refractCImage.getTitle() + " create ignore") mergedImage = WindowManager.getImage("Composite") params = ("reference_channel=2 application_channel=1 automatic_operation generate_log " + "max_slice=43 surface_slice=87") IJ.run(mergedImage,"Refractive Signal Loss Correction",params) dataImage = WindowManager.getImage("App Corrected") mergedImage.close()
# pt = Plot(plottitle, "Frames", "Intensity") pt = Plot(plottitle, "Frames", "Intensity") pt.setLimits(0, pathlenMax + 1, meanMin, maxMax) pt.setColor(Color.red) pt.addPoints(jframes, jmean, pt.LINE) pt.setColor(Color.lightGray) pt.addPoints(jframes, jmax, pt.LINE) # pt.addPoints(jframes, jmean, pt.CIRCLE) # pt.draw() pt.show() GdilateIter = 2 imp = IJ.getImage() chsA = CS.split(imp) impc1 = chsA[0] impc2 = chsA[1] IJ.run("Clear Results", "") IJ.run(impc1, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") IJ.run(impc2, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") impbin, rt = segmentNuc(impc2, GdilateIter) imprim = extractRIM(impbin, GdilateIter) rt.show("Results") cxA, cyA, bxA, byA, widthA, heightA, frameA, indexA = parseResultsTable(rt) hasNextFrame = checkPresenceinNextFrame(impbin, rt, cxA, cyA, frameA) nextFrame = linkNucelus(cxA, cyA, frameA, hasNextFrame) """ for i in nextFrame: print i, 'slice', frameA[i], 'to ', nextFrame[i]