def main(): # Open a .ome.tif image from the Flexoscope. impath = IJ.getFilePath("Choose .ome.tiff file") channels = Opener.openUsingBioFormats(impath) # Show image # imp.show() # straight to channels object sames memory. # Split channels. channels = ChannelSplitter().split(channels) # Process channel 1. # subtractzproject(imp, projectionMethod="Median") channels[1] = ImagePlus() channels.append(ImagePlus()) channels[1] = subtractzproject(channels[0]) IJ.run(channels[0], "Enhance Contrast...", "saturated=0.3 normalize process_all use") IJ.run(channels[0], "8-bit", "") IJ.run(channels[1], "Square", "stack") IJ.run(channels[1], "Enhance Contrast...", "saturated=0.3 normalize process_all use") IJ.run(channels[1], "8-bit", "") # Merge channels. merge = RGBStackMerge().mergeChannels(channels, True) # boolean keep merge.show()
def merge_kymographs(kym1_imp, kym2_imp, params): """Merge two kymographs""" mrg_imp = RGBStackMerge().mergeChannels([kym1_imp, kym2_imp], True) mrg_imp.setTitle("Merged " + params.labeled_species + " intensity and curvature kymograph") mrg_imp.show() return mrg_imp
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 _horcombine(imp_collection): """Combine a list of stacks with the same dimensions horizontally. Args: imp_collection: A list of stacks. Returns: A horizontally combined stack of the input images. """ comb = imp_collection[0] comb_channels = ChannelSplitter().split(comb) comb_channels = [i.getImageStack() for i in comb_channels] for imp in imp_collection: if imp == imp_collection[0]: continue imp_channels = ChannelSplitter().split(imp) imp_channels = [i.getImageStack() for i in imp_channels] comb_channels = [ StackCombiner().combineHorizontally(i, j) for i, j in zip(comb_channels, imp_channels) ] comb_channels = [ ImagePlus("C{}".format(i + 1), channel) for i, channel in enumerate(comb_channels) ] impout = RGBStackMerge().mergeChannels(comb_channels, False) # boolean keep return impout
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 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 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 mergechannels(self, root, sortedchannels, onGPU=False): ''' Merge sorted channels(list of titles) under a given root title. If ColorMerger was initialized with a savefolder it will try to save img in savefolder else will merge channels, close original images and show the resulting composite. ''' IJ.log("\n## Merging <{0}>".format(root)) imgpaths = [ os.path.join(self.imgfolder, title) if title else None for title in sortedchannels ] imps = [imageloader(path) if path else None for path in imgpaths] for img in imps: if img: calibration = img.getCalibration() break merger = RGBStackMerge() try: composite = merger.mergeChannels(imps, False) except (Exception, java.lang.Exception): t_name = current_thread().name IJ.log( "# {0}\t{1} images skipped as channels have different dimensions" .format(t_name, root)) return composite.setCalibration(calibration) if self.savefolder: save_string = os.path.join(self.savefolder, root) try: FileSaver(composite).saveAsTiff(save_string) IJ.log("{0}".format(save_string)) except (Exception, java.lang.Exception) as e: IJ.log( "ij.io.FileSaver raised an {0} exception while trying to save img '{1}' as '{2}'. Skipping image." .format(e, root, save_string)) else: composite.setTitle(root) [imp.close() for imp in imps if imp] composite.show()
def do_tubefitting(im_path=im_test_path, metadata_path=metadata_test_path, output_path=output_path, save_output=False): # todo: fix things so that all operations use a consistent definition of background rather than changing Prefs on the fly... Prefs.blackBackground = False info = PrescreenInfo() info.load_info_from_json(metadata_path) z_xy_ratio = abs( info.get_z_plane_spacing_um()) / info.get_xy_pixel_size_um() #z_xy_ratio = 1.0; bfimp = bf.openImagePlus(im_path) imp = bfimp[0] imp.show() IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") imp = utils.downsample_for_isotropy(imp, extra_downsample_factor=1.0, info=info) rot_seg_imp, rot_proj_imp, egfp_mch_imps = split_and_rotate(imp, info) depth = rot_seg_imp.getNSlices() if rot_seg_imp.getNSlices( ) > rot_seg_imp.getNFrames() else rot_seg_imp.getNFrames() width = rot_seg_imp.getWidth() height = int(round(rot_seg_imp.getHeight() * z_xy_ratio)) # Apply 3d MEDIAN FILTER to denoise and emphasise vessel-associated voxels fit_basis_imp = threshold_and_binarise(rot_seg_imp, z_xy_ratio) fit_basis_imp.setTitle("fit_basis_imp") fit_basis_imp.show() # plane-wise, use binary-outline # say the non-zero points then make up basis for fitting to be performed per http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html rois = [] centres = [] major_axes = [] roi_imp = IJ.createImage("rois", width, height, depth, 32) pts_stack = ImageStack(width, height + 1) IJ.run(imp, "Line Width...", "line=3") for zidx in range(fit_basis_imp.getNSlices()): fit_basis_imp.setZ(zidx + 1) IJ.run(fit_basis_imp, "Outline", "slice") IJ.run(fit_basis_imp, "Create Selection", "") roi = fit_basis_imp.getRoi() fit_basis_imp.killRoi() pts = [(pt.x, pt.y) for pt in roi.getContainedPoints()] clean_pts = convex_hull_pts(pts) clean_pts = [(x, z_xy_ratio * y) for (x, y) in clean_pts] # make a stack of clean points... ip = FloatProcessor(width, height + 1) pix = ip.getPixels() for pt in clean_pts: pix[int(pt[1]) * width + int(pt[0])] = 128 pts_stack.addSlice(ip) centre, angle, axl = ellipse_fitting.fit_ellipse(clean_pts) major_axes.append(max(axl)) centres.append(centre) rot_seg_imp.setZ(zidx + 1) ellipse_roi = ellipse_fitting.generate_ellipse_roi(centre, angle, axl) rois.append(ellipse_roi) IJ.run(imp, "Line Width...", "line=1") cal = imp.getCalibration() smooth_centres, tangent_vecs = generate_smoothed_vessel_axis( centres, pixel_size_um=cal.pixelDepth) for zidx in range(fit_basis_imp.getNSlices()): centre = smooth_centres[zidx] major_axis = major_axes[zidx] ellipse_roi = EllipseRoi(centre[0] - 2, centre[1], centre[0] + 2, centre[1], 1.0) roi_imp.setZ(zidx + 1) roi_imp.setRoi(ellipse_roi) IJ.run(roi_imp, "Set...", "value=" + str(roi_imp.getProcessor().maxValue()) + " slice") pts_stack_imp = ImagePlus("Cleaned points", pts_stack) pts_stack_imp.setTitle("pts_stack_imp") pts_stack_imp.show() rot_seg_imp.changes = False rot_seg_imp.close() egfp_imp = egfp_mch_imps[0] mch_imp = egfp_mch_imps[1] imps_to_combine = [egfp_mch_imps[1], egfp_mch_imps[0], roi_imp] egfp_imp.show() mch_imp.show() roi_imp.show() print("box height um = " + str(roi_imp.getNSlices() * info.get_xy_pixel_size_um())) IJ.run( egfp_imp, "Size...", "width=" + str(width) + " height=" + str(height) + " depth=" + str(depth) + " average interpolation=Bilinear") IJ.run( mch_imp, "Size...", "width=" + str(width) + " height=" + str(height) + " depth=" + str(depth) + " average interpolation=Bilinear") #IJ.run("Merge Channels...", "c1=[" + mch_imp.getTitle() + # "] c2=[" + egfp_imp.getTitle() + # "] c7=[" + roi_imp.getTitle() + "] create keep"); composite_imp = RGBStackMerge().mergeChannels(imps_to_combine, False) print(composite_imp) composite_imp.show() print("end of vessel centerline id step, image dims = ({}x{}x{})".format( composite_imp.getWidth(), composite_imp.getHeight(), composite_imp.getNSlices())) WaitForUserDialog("pause").show() # do qc here? #WM.getImage("Composite").addImageListener(UpdateRoiImageListener(rois)); IJ.run(roi_imp, "8-bit", "") if save_output: FileSaver(composite_imp).saveAsTiffStack( os.path.join(output_path, "segmentation result.tif")) print(roi_imp) FileSaver(roi_imp).saveAsTiff( os.path.join(output_path, "vessel axis.tif")) egfp_imp.changes = False mch_imp.changes = False roi_imp.changes = False fit_basis_imp.changes = False pts_stack_imp.changes = False egfp_imp.close() mch_imp.close() #roi_imp.close(); fit_basis_imp.close() pts_stack_imp.close() zcoords = [i for i in range(composite_imp.getNSlices())] xyz_smooth_centres = [(x, y, z) for ((x, y), z) in zip(smooth_centres, zcoords)] composite_imp2 = straighten_vessel(composite_imp, xyz_smooth_centres, save_output=True) composite_imp3 = straighten_vessel(composite_imp2, xyz_smooth_centres, it=2, save_output=True) return composite_imp3
IJ.setThreshold(green_coloc,summary["Green" + "-threshold-used"], 255); IJ.run(green_coloc, "Convert to Mask", ""); pa_green.analyze(green_coloc) # green_coloc.show() rt4 = ResultsTable() ta_coloc2=Analyzer(green_coloc,Measurements.INTEGRATED_DENSITY ,rt4); ta_coloc2.measure(); greenIntensity=(rt4.getColumnAsDoubles(rt4.getColumnIndex("IntDen")))[0]; ic_coloc =ImageCalculator(); coloc_img=ic_coloc.run("Multiply create",red_coloc,green_coloc); rt5 = ResultsTable() ta_coloc3=Analyzer(coloc_img,Measurements.INTEGRATED_DENSITY ,rt5); ta_coloc3.measure(); totalIntensity=(rt5.getColumnAsDoubles(rt5.getColumnIndex("IntDen")))[0]; rgb=RGBStackMerge(); composite=rgb.mergeChannels([red_coloc,green_coloc],False); composite.show(); fs=FileSaver(composite); fs.saveAsJpeg(outputDirectory + '/' + "coloc_"+filename); composite.close(); if redIntensity == 0: summary["Red-Green-Coloc-%"]= "NaN" else: summary["Red-Green-Coloc-%"]= float (totalIntensity*100/redIntensity) if greenIntensity == 0: summary["Green-Green-Coloc-%"]= "NaN" else: summary["Green-Red-Coloc-%"]= float (totalIntensity*100/greenIntensity)
# for each channel. channels = {} for image_file in image_files: channel = re.search('channel(\d+)_', image_file).group(1) if channel in channels: channels[channel] += 1 else: channels[channel] = 1 if len(channels) > 7: print 'Images with more than 7 channels are not currently supported by the Merge Channels operation.' sys.exit(1) # Open an image sequence for each channel. stacks = [] for channel in channels: num_frames = channels[channel] IJ.run('Image Sequence...', 'open=%s file=channel%s sort' % (image_files[0], channel)) stack = IJ.getImage() stack.setTitle(channel) stack.setDimensions(1, 1, num_frames) # TODO Don't hardcode the number of slices stacks.append(stack) merged_image = RGBStackMerge().mergeChannels(stacks, False) merged_image.setTitle(dir_name) # TODO Alternatively, we could upload directly to OMERO. But that probably # would not work in headless mode. IJ.run(merged_image, 'OME-TIFF...', 'save=%s.ome.tif compression=Uncompressed' % image_dir_path)
for f in image_list: if (w_re.search(f) != None and int(w_re.search(f).group()[0:3]) != 405): #Leave out DAPI wave_lengths.append(int(w_re.search(f).group()[0:3])) break channel_no = len(wave_lengths) print 'Detected ' + str( channel_no) + ' channel(s) with wavelength(s) ' + str(wave_lengths) return wave_lengths, channel_no oc = OverlayCommands() rt = ResultsTable() measured = rt.getResultsTable() cs = ChannelSplitter() cm = RGBStackMerge() zp = ZProjector() zp.setMethod(ZProjector.AVG_METHOD) IJ.run("Close All") #Find images and wavelengths imagelist = [ f for f in os.listdir(str(inputpath)) if (('.tif' in f.lower()) and ('thumb' not in f.lower())) ] wavelengths, nChannels = get_apical_channels(imagelist, 6) tm_wavelength = [x for x in wavelengths if not x == ref_wavelength][0] #Sort image files regexDetect = re.compile(
z boolean c char b byte h short i int l long f float d double """ ja = jarray.array([0, 1, 2, 3], 'i') print(ja) """ What if you want to make a java array of a specific class? You could then name the class as the second argument. For example """ img_dir = git_home + "/tips/ImageJ/" imp_blobs_1 = IJ.openImage("http://imagej.nih.gov/ij/images/blobs.gif") IJ.run(imp_blobs_1, "Red", "") imp_blobs_2 = imp_blobs_1.duplicate() IJ.run(imp_blobs_2, "Green", "") imp_blobs_3 = imp_blobs_1.duplicate() IJ.run(imp_blobs_3, "Blue", "") img_array = jarray.array([imp_blobs_1, imp_blobs_2, imp_blobs_3], ImagePlus) gray_stack = RGBStackMerge().mergeHyperstacks(img_array, True) gray_stack.show() gray_comp = RGBStackMerge().mergeChannels(img_array, False) gray_comp.show()