if len(position) > 2: IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_zpos+" value=["+str(position[2])+"] windows=REG_SZ") def saveOutputImg(impOut, filepath, diranalyzed): if impOut is not None: analyzeDir = os.path.join(os.path.dirname(filepath), diranalyzed) if not os.path.isdir(analyzeDir):
def saveImp(self, filePath, imp): cDir = path.split(filePath)[0] if not path.exists(cDir): print "Making directory " + cDir mkdir(cDir) IJ.saveAs(imp, ".tiff", filePath) print "Saved as " + filePath + ".tiff"
def make_mask_file(p, imp): x_min = p['mask_roi'][0] y_min = p['mask_roi'][1] z_min = p['mask_roi'][2] x_width = p['mask_roi'][3] y_width = p['mask_roi'][4] z_width = p['mask_roi'][5] imp_mask = imp.duplicate() IJ.setBackgroundColor(0, 0, 0); IJ.run(imp_mask, "Select All", ""); IJ.run(imp_mask, "Clear", "stack"); IJ.run(imp_mask, "Select None", ""); #IJ.run(imp_mask, "8-bit", ""); for iSlice in range(z_min, z_min+z_width): imp_mask.setSlice(iSlice) ip = imp_mask.getProcessor() ip.setColor(1) ip.setRoi(x_min, y_min, x_width, y_width) ip.fill() mask_filepath = os.path.join(p['output_folder'],'mask.tif') IJ.saveAs(imp_mask, 'TIFF', mask_filepath) return mask_filepath
def runPoreDetection(inputImp, data, ops, display): name=inputImp.getTitle() inputDataset=Utility.getDatasetByName(data, name) detectionParameters=DetectionParams() roi=inputImp.getRoi() if (roi is None): message=name+": "+Messages.NoRoi IJ.write(message) return roi=inputImp.getRoi().clone(); header, statslist=poreDetectionTrueColor(inputImp, inputDataset, roi, ops, data, display, detectionParameters) directory, overlayname, roiname=Utility.createImageNames(inputImp) statsname=directory+'truecolor_stats.csv' IJ.save(inputImp, overlayname); IJ.saveAs(inputImp, "Selection", roiname); header.insert(0,Messages.FileName) statslist.insert(0,name) print header print statslist ExportDataFunction.exportSummaryStats(statsname, header, statslist)
def analyse(imp, root, filename): imp.show() print "" print(imp.getTitle()) print "**********************************" channels=(1,2,3) thresholds=(3000,1000,8000) # day... backgrounds=thresholds #(175,0,275) #IJ.run(imp, "Gaussian Blur...", "sigma=1 stack"); impA = [] sumIntensities = [] sumIntensitiesBW = [] for iChannel in channels: # general issues: # - intensity decreases along z # measure total intensity # - bg subtraction? impc = extractChannel(imp, iChannel, 1) impbw = threshold(impc, thresholds[iChannel-1]) impcBGcorr = Duplicator().run(impc) IJ.run(impcBGcorr, "Subtract...", "value="+str(backgrounds[iChannel-1])+" stack"); sumIntensities.append(measureSumIntensity3D(impcBGcorr)) # measure number of pixels containing a signification signal # - what is good here for thresholding and preprocessing? #impbw = autoThreshold(impc, "Default") #impbw.setTitle("bw"+str(iChannel)) #impbw.show() impA.append(impbw) sumIntensitiesBW.append(measureSumIntensity3D(impbw)/255) print "intensities,",str(sumIntensities)[1:-1] print "volumes,",str(sumIntensitiesBW)[1:-1] sumIntensitiesNorm = [x / sumIntensitiesBW[1] for x in sumIntensities] sumIntensitiesBWNorm = [x / sumIntensitiesBW[1] for x in sumIntensitiesBW] print "intensities normalised,",str(sumIntensitiesNorm)[1:-1] print "volumes normalised,",str(sumIntensitiesBWNorm)[1:-1] impMerge = RGBStackMerge.mergeChannels(array(impA, ImagePlus), False) impMerge.setDisplayMode(IJ.COLOR); impMerge.setC(1); IJ.run(impMerge, "Green", ""); impMerge.setC(2); IJ.run(impMerge, "Grays", ""); impMerge.setC(3); IJ.run(impMerge, "Blue", ""); impMerge.show() IJ.saveAs(impMerge, "Tiff", os.path.join(root, filename + "--segmented.tif"));
def concatenateImagePlus(files, outfile): """Concatenate images contained in files and save in outfile""" options = ImporterOptions() options.setId(files[0]) options.setVirtual(1) options.setOpenAllSeries(1) options.setQuiet(1) images = BF.openImagePlus(options) imageG = images[0] nrPositions = len(images) options.setOpenAllSeries(0) nslices = imageG.getNSlices() nframes = len(files) nchannels = imageG.getNChannels() luts = imageG.getLuts() for i in range(0, nrPositions): concatImgPlus = IJ.createHyperStack( "ConcatFile", imageG.getWidth(), imageG.getHeight(), imageG.getNChannels(), imageG.getNSlices(), len(files), imageG.getBitDepth()) concatStack = ImageStack(imageG.getWidth(), imageG.getHeight()) IJ.showStatus("Concatenating files") for file_ in files: try: print '...', basename(file_) options.setSeriesOn(i, 1) options.setId(file_) image = BF.openImagePlus(options)[0] imageStack = image.getImageStack() sliceNr = imageStack.getSize() for j in range(1, sliceNr+1): concatStack.addSlice(imageStack.getProcessor(j)) image.close() options.setSeriesOn(i, 0) except Exception, e: IJ.log("ERROR") IJ.log(file_ + str(e)) raise IJ.showProgress(files.index(file_), len(files)) concatImgPlus.setStack(concatStack, nchannels, nslices, nframes) concatImgPlus.setCalibration(image.getCalibration()) concatImgPlus.setOpenAsHyperStack(True) concatImgPlus.setLuts(luts) concatImgPlus.close() IJ.saveAs(concatImgPlus, "Tiff", outfile)
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! # 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 IJ.saveAs(imp, "Tiff", os.path.join(saveDir, fileName)); imp.close()
def getCompositeImgs(): BF, PI, filepath = getImgs() for i in range(len(BF)): IJ.open(filepath + '/' + PI[i]) IJ.run('Auto Threshold', 'method=Yen ignore_black white') IJ.open(filepath + '/' + BF[i]) IJ.run('8-bit') IJ.run('Merge Channels...', 'c1=%s c4=%s create'%(PI[i], BF[i])) IJ.run('Flatten') if 'processed' not in os.listdir(filepath): os.mkdir(filepath + '/processed/') name = BF[i].split('bf') IJ.saveAs('Tiff', filepath + '/processed/' + name[0] + '_COMPOSITE_' + name[1]) IJ.run('Close') print '[+] Processed image: %s' %(name[0] + '_COMPOSITE_' + name[1]) return 0
def runPoreDetection(inputImp, data, ops, display): # in this step get the image in the "imagej2" dataset format # this way we can take advantage of some of the new imagej2 functionality name=inputImp.getTitle() inputDataset=Utility.getDatasetByName(data, name) # this structure keeps track of detection parameters detectionParameters=DetectionParams() roi=inputImp.getRoi() # check if there is an roi on the image. If not return an error if (roi is None): message=name+": "+Messages.NoRoi IJ.write(message) return # clone the roi roi=inputImp.getRoi().clone(); # call the function that processes the UV image roilist, statslist, statsheader=poreDetectionUV(inputImp, inputDataset, roi, ops, data, display, detectionParameters) # get the names for the images that will be saved directory, overlayname, roiname=Utility.createImageNames(inputImp) # name of file to save summary stats statsname=os.path.join(directory, 'stats.csv') # save the image with overlay IJ.save(inputImp, overlayname); # save the roi IJ.saveAs(inputImp, "Selection", roiname); statsheader.insert(0,Messages.FileName) statslist.insert(0,name) ExportDataFunction.exportSummaryStats(statsname, statsheader, statslist) print statsname print statsheader print statslist
def ij_binary_skeletonize(impath_in, impath_out): """Load image `impath`, skeletonize it, and save it to the same file. Parameters ---------- impath_in : string Path to a 3D image file. impath_out : string Path to which to write the skeleton image file. Returns ------- None """ imp = IJ.openImage(impath_in) IJ.run(imp, "Skeletonize (2D/3D)", "") IJ.run(imp, "Analyze Skeleton (2D/3D)", "prune=none prune") IJ.saveAs(imp, "Tiff", impath_out) imp.close()
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 main(): IJ.open(dir_path+file_name) #IJ.open("/Users/richardhart/Dropbox/AMRE/2013-08-03-96dpiPrintTesting-DifferentZheights-Sample.png") IJ.selectWindow(file_name) #IJ.selectWindow("2013-08-03-96dpiPrintTesting-DifferentZheights-Sample.png") IJ.run("Options...", "iterations=1 count=1 edm=Overwrite") #setting binary mask options IJ.run("Make Binary") #converting a picture o a binary image. IJ.run("Watershed") #Watershed breaks appart blobs in a binary image into smaller pieces IJ.run("Set Measurements...", "area mean standard modal min centroid center perimeter bounding fit shape feret's integrated median skewness kurtosis area_fraction stack redirect=None decimal=3") #Specifying what measurements to take IJ.run("Analyze Particles...", "size=0-Infinity circularity=0.00-1.00 show=Ellipses display clear include") #taking measurements IJ.selectWindow("Results") #Making sure the results are selected so the window's data will be saved IJ.saveAs("Results", dir_path + "Results.txt"); #IJ.saveAs("/Users/richardhart/Dropbox/AMRE/Results.txt")
def convert_before_saving_as_tiff( image_plus ): # The bUnwarpJ plug-in produces TIFF image stacks consisting of 3 # slices which can be viewed in ImageJ. The 3 slices are: 1) the # registered image, 2) the target image and 3) the black/white warp # image. When running bUnwarpJ from the command line (as these # Galaxy wrappers do) the initial call to IJ.openImage() (to open the # registered source and target images produced by bUnwarpJ) in the # tool's jython_script.py returns an ImagePlus object with a single # slice which is the "generally undesired" slice 3 discussed above. # However, a call to IJ.saveAs() will convert the single-slice TIFF # into a 3-slice TIFF image stack (as described above) if the selected # format for saving is TIFF. Galaxy supports only single-layered # images, so to work around this behavior, we have to convert the # image to something other than TIFF so that slices are eliminated. # We can then convert back to TIFF for saving. There might be a way # to do this without converting twice, but I spent a lot of time looking # and I have yet to discover it. tmp_dir = imagej2_base_utils.get_temp_dir() tmp_out_png_path = imagej2_base_utils.get_temporary_image_path( tmp_dir, 'png' ) IJ.saveAs( image_plus, 'png', tmp_out_png_path ) return IJ.openImage( tmp_out_png_path )
def analyze(folder_name, file_name): # prepare af.close_all_image_windows() #af.close_non_image_window("Results") # load imp = Opener().openImage(folder_name, file_name) #imp = IJ.getImage() # segment imp_scaled = af.scale(imp, 0.25, 0.25, 1) #imp_scaled = af.scale(imp, 0.25, 0.25, 1) calibration = imp_scaled.getCalibration() imp_corr = af.attenuation_correction(imp_scaled, 15.0, 8.0) imp_bw = af.auto_threshold(imp_corr, "Yen") imp_label = af.watershed_3d(imp_bw, 8) # filter objects based on intensity or roughness=surface/volume? # measure af.clear_results_table_if_exists() imp_label.setCalibration(calibration) results_table = af.geometrical_measure_3D(imp_label) #results_table = af.intensity_measure_3D(imp_scaled, imp_label) # create images for visual inspection imp_outlines = af.make_outline_image(imp_label) IJ.run(imp_outlines, "Fire", "") imp_merged = af.merge_images(imp_scaled, imp_outlines, force_same_bit_depth=True) #imp_merged.show() # configure and run 3D Objects Counter #imp_outlines = af.objects_counter_3d(imp_bw, imp_scaled, "volume nb_of_obj._voxels integrated_density mean_gray_value", threshold=1, vol_min=50, vol_max=100000) #imp_merged = af.merge_images(imp_outlines, imp_scaled) # save file_name_out = file_name + "--fiji-out.tif" IJ.saveAs(imp_merged, "TIFF", os.path.join(folder_name, file_name_out)) file_name_out = file_name + "--fiji-out.csv" results_table.save(os.path.join(folder_name, file_name_out))
def draw_classes(inputfile,data): pathname,filename = os.path.split(inputfile) # last subdir is for well ## TODO ## support multiple plates, read plate and well from csv well = os.path.basename(pathname) # create output directory outputdir = os.path.join(OUTPUTROOT,well) if not os.path.isdir(outputdir): os.makedirs(outputdir) # create output filename head,tail = os.path.splitext(filename) outputfilename = head + "_classes" + tail outputfilename = os.path.join(outputdir,outputfilename) print outputfilename imp = IJ.openImage(inputfile).duplicate() IJ.run(imp,"RGB Color","") for d in data: x = int(float(d[0])) y = int(float(d[1])) c = int(float(d[2])) classname = classes[str(c)] colorname = colors[classname] color = colormap[colorname] #print colorname roi = PointRoi(x,y) roi.setDefaultMarkerSize("Large") roi.setStrokeColor(colormap[colorname]) imp.getProcessor().drawRoi(roi) IJ.saveAs(imp,"png",outputfilename)
def save_hyperstack_as_image_sequence(imp, path): # make dir if not os.path.isdir(path): os.mkdir(path) #imp.show() ssize = imp.getStackSize() titleext = imp.getTitle() #print titleext title = os.path.splitext(titleext)[0] dimA = imp.getDimensions() print "Title",title," ----- Dimensions",dimA for c in range(dimA[2]): for z in range(dimA[3]): for t in range(dimA[4]): # imagej is one-based and we save zero-based numberedtitle = \ title + "--C" + IJ.pad(c, 2) + \ "--Z" + IJ.pad(z, 4) + \ "--T" + IJ.pad(t, 4) + ".tif" stackindex = imp.getStackIndex(c+1, z+1, t+1) # imagej is one-based aframe = ImagePlus(numberedtitle, imp.getStack().getProcessor(stackindex)) IJ.log("saving: " + os.path.join(path, numberedtitle)) IJ.saveAs(aframe, "TIFF", os.path.join(path, numberedtitle))
def batch_open_images(pathImage, pathSplit, file_typeImage=None, name_filterImage=None, recursive=False): '''Open all files in the given folder. :param path: The path from were to open the images. String and java.io.File are allowed. :param file_type: Only accept files with the given extension (default: None). :param name_filter: Reject files that contain the given string (default: wild characters). :param recursive: Process directories recursively (default: False). ''' # Converting a File object to a string. if isinstance(pathImage, File): pathImage = pathImage.getAbsolutePath() def check_type(string): '''This function is used to check the file type. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the check on. ''' if file_typeImage: # The first branch is used if file_type is a list or a tuple. if isinstance(file_typeImage, (list, tuple)): for file_type_ in file_typeImage: if string.endswith(file_type_): # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if file_type is a string. elif isinstance(file_typeImage, string): if string.endswith(file_typeImage): return True else: return False return False # Accept all files if file_type is None. else: return True def check_filter(string): '''This function is used to check for a given filter. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the filtering on. ''' if name_filterImage: # The first branch is used if name_filter is a list or a tuple. if isinstance(name_filterImage, (list, tuple)): for name_filter_ in name_filterImage: if name_filter_ in string: # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if name_filter is a string. elif isinstance(name_filterImage, string): if name_filterImage in string: return True else: return False return False else: # Accept all files if name_filter is None. return True # We collect all files to open in a list. path_to_Image = [] # Replacing some abbreviations (e.g. $HOME on Linux). path = os.path.expanduser(pathImage) path = os.path.expandvars(pathImage) # If we don't want a recursive search, we can use os.listdir(). if not recursive: for file_name in os.listdir(pathImage): full_path = os.path.join(pathImage, file_name) if os.path.isfile(full_path): if check_type(file_name): if check_filter(file_name): path_to_Image.append(full_path) # For a recursive search os.walk() is used. else: # os.walk() is iterable. # Each iteration of the for loop processes a different directory. # the first return value represents the current directory. # The second return value is a list of included directories. # The third return value is a list of included files. for directory, dir_names, file_names in os.walk(pathImage): # We are only interested in files. for file_name in file_names: # The list contains only the file names. # The full path needs to be reconstructed. full_path = os.path.join(directory, file_name) # Both checks are performed to filter the files. if check_type(file_name): if check_filter(file_name) is False: # Add the file to the list of images to open. path_to_Image.append([ full_path, os.path.basename(os.path.splitext(full_path)[0]) ]) # Create the list that will be returned by this function. Images = [] for img_path, file_name in path_to_Image: # IJ.openImage() returns an ImagePlus object or None. imp = IJ.openImage(img_path) stack = imp.getStack() print(img_path) if check_filter(file_name): continue else: for i in range(1, imp.getNSlices() + 1): slice = stack.getProcessor(i) TwoDstack = ImageStack(imp.width, imp.height) TwoDstack.addSlice(str(i), slice.toFloat(0, None)) TwoDimp = ImagePlus(str(i - 1), TwoDstack) IJ.saveAs(TwoDimp, '.tif', str(pathSplit) + "/" + str(i - 1)) #print(img_path, RoiName) Images.append(imp) return Images
rm.runCommand("Show All with labels") #for each image open.. for image in image_titles: imp = WindowManager.getImage(image) baseName = os.path.splitext(image)[0] #get the name without extension roiFile = baseName + "_ROISet.zip" #make the name for the text file roiFilePath = os.path.join(roiDir, roiFile) #make the path for the text file print(roiFilePath) IJ.openImage(roiFilePath) #open the roi text file rm.runCommand("Select All") #select all rois rm.runCommand(imp, "Measure") #measure all rois rm.runCommand(imp, "Show All") #show all rois imp2 = imp.flatten() #create a flattened key with rois and labels imp2.setTitle("labels_" + baseName + ".tif") imp2.show() rm.runCommand("Select All") rm.runCommand("Delete") #delete all rois in manager imp.close() rm.runCommand(imp, "Show None") windowName = imp2.getTitle() flatPath = os.path.join(roiDir, windowName) IJ.saveAsTiff(imp2, flatPath) #save flattened image csvFile = os.path.join(roiDir, "Measurements.csv") IJ.saveAs("Results", csvFile) #export measurements as csv file
for l in distance_lines[1:len(distance_lines)-1]: index, frame, distance, ch0dist, ch1dist, ch0vol, ch1vol = l.split("\t") # find respective frame in ch0 and ch1 dot list. Problem, if both dots have same volume. Vol can be identical! ch0DotList = dotListToSingle( [d for d in ch0_dots if (d.getFrame() == int(float(frame)) and d.getVol() == int(float(ch0vol)) )] ) ch1DotList = dotListToSingle( [d for d in ch1_dots if (d.getFrame() == int(float(frame)) and d.getVol() == int(float(ch1vol)) )] ) frameList.append(fr(frame, distance, ch0DotList, ch1DotList)) # fill up table with unsegmented frames. presentFrames = [f.getFrameNo() for f in frameList] missingFrames = [f for f in range(max(presentFrames)) if f not in presentFrames] for f in missingFrames: frameList.append(fr(f, None, None, None)) #sort by frame frameList.sort(key=lambda x: x.getFrameNo()) c = cell(frameList) # write to file. c.exportData(saveFolder +"/val_" + image.group('name') + ".csv") # save Z-projection image with marked dots detDots = WindowManager.getImage("DetectedDots") detDots.copyScale(imp) IJ.saveAs(detDots, ".tiff", saveFolder + "/zi_"+image.group('name')) # save the overlay with connecting line print "Saving as " + image.group('name') detDots.close() IJ.log("Finished")
imDir = IJ.getDirectory("image") # 現在のactiveなImageのDirectoryをimDirとして取得 os.chdir(imDir + "..") # 現在の作業ディレクトリをimDirのひとつ上に指定 u1_Dir = os.getcwd() # このディレクトリの base = os.path.basename(u1_Dir) # basenameを保存ファイル名として使うために取得する os.chdir(u1_Dir + "/..") u2_Dir = os.getcwd() # imageDirectoryのふたつ上の階層に if not os.path.exists(u2_Dir + os.sep + "analyze"): # anlyzeというフォルダを作成 os.makedirs(u2_Dir + os.sep + "analyze") svDir = u2_Dir + os.sep + "analyze" # ここを保存先とする wm.setWindow(wm.getWindow("Log")) IJ.saveAs("Text", svDir + os.sep + base + "-analyze_MT_dynamics") n = len(dls) seq_growth_dls = [] seq_growth_dl = 0 seq_shrink_dls = [] seq_shrink_dl = 0 for i in range(len(states)): seq_growth_dls.append([]) seq_shrink_dls.append([]) for i in range(len(states)): for j in range(len(states[i])): if states[i][j] == "growth": if j < len(states[i]) - 1 and states[i][j] == states[i][j + 1]:
print 'Average Radius:' , mean_radius # Create the overlay image overlayImage = image.duplicate() IJ.run(overlayImage, "RGB Color", "") IJ.run(overlayImage, 'Specify...', 'width=' + str(2*mean_radius) + \ ' height=' + str(2*mean_radius) + \ ' x=' + str(mean_cx) + \ ' y=' + str(mean_cy) + ' oval centered'); roi = overlayImage.getRoi() overlayImage.setOverlay(roi, Color(246, 27, 27), 10, None) overlayImage = overlayImage.flatten(); # Now add the overlay image as the first stack newStack = image.createEmptyStack() newStack.addSlice(overlayImage.getProcessor()) newStack.addSlice(image.getProcessor()) image.setStack(newStack) directory = IJ.getDirectory('image') print directory name = image.getShortTitle() print name # Now save results table. Then done. IJ.saveAs('Measurements', directory + name + '.txt') print 'Done saving measurement table!' # Now overwrite the original image IJ.saveAsTiff(image, directory + name + '.tif')
if sys.argv[ -1 ].lower() in [ 'true' ]: mono = True else: mono = False if mono: # bUnwarpJ has been called with the -mono param. source_tiff_path = sys.argv[ -4 ] source_datatype = sys.argv[ -3 ] source_path = sys.argv[ -2 ] else: source_tiff_path = sys.argv[ -7 ] source_datatype = sys.argv[ -6 ] source_path = sys.argv[ -5 ] target_tiff_path = sys.argv[ -4 ] target_datatype = sys.argv[ -3 ] target_path = sys.argv[ -2 ] # Save the Registered Source Image. registered_source_image = IJ.openImage( source_tiff_path ) if source_datatype == 'tiff': registered_source_image = jython_utils.convert_before_saving_as_tiff( registered_source_image ) IJ.saveAs( registered_source_image, source_datatype, source_path ) if not mono: # Save the Registered Target Image. registered_target_image = IJ.openImage( target_tiff_path ) if target_datatype == 'tiff': registered_target_image = jython_utils.convert_before_saving_as_tiff( registered_target_image ) IJ.saveAs( registered_target_image, target_datatype, target_path )
def main(): # Prepare directory tree for output. indir = IJ.getDirectory("input directory") outdir = IJ.getDirectory(".csv output directory") c1dir = os.path.join(outdir, "Channel1") c2dir = os.path.join(outdir, "Channel2") c3dir = os.path.join(outdir, "Channel3") c4dir = os.path.join(outdir, "Channel4") channelsdir = os.path.join(outdir, "Channels") if not os.path.isdir(c1dir): os.mkdir(c1dir) if not os.path.isdir(c2dir): os.mkdir(c2dir) if not os.path.isdir(c3dir): os.mkdir(c3dir) if not os.path.isdir(c4dir): os.mkdir(c4dir) if not os.path.isdir(channelsdir): os.mkdir(channelsdir) # Collect all file paths in the input directory files = readdirfiles(indir) # Initialize the results tables. c1Results = ResultsTable() c2Results = ResultsTable() c3Results = ResultsTable() c4Results = ResultsTable() for file in files: IJ.log("File: {}/{}".format(files.index(file) + 1, len(files))) if file.endswith('.tif'): # Open .tiff file as ImagePlus. imp = Opener().openImage(file) imp = ZProjector.run(imp, "max") # imp = stackprocessor(file, # nChannels=4, # nSlices=7, # nFrames=1) channels = ChannelSplitter.split(imp) name = imp.getTitle() # For every channel, save the inverted channel in grayscale as .jpg. for channel in channels: IJ.run(channel, "Grays", "") IJ.run(channel, "Invert", "") jpgname = channel.getShortTitle() jpgoutfile = os.path.join(channelsdir, "{}.jpg".format(jpgname)) IJ.saveAs(channel.flatten(), "Jpeg", jpgoutfile) IJ.run(channel, "Invert", "") # OPTIONAL - Perform any other operations (e.g. crossexcitation compensation tasks) before object count. c2name = channels[2].getTitle() cal = channels[2].getCalibration() channels[2] = ImagePlus( c2name, ImageCalculator().run("divide create 32-bit", channels[2], channels[3]).getProcessor( ) # This removes AF647 bleed-through ) channels[2].setCalibration(cal) # Settings for channel1 threshold. c1 = countobjects(channels[0], c1Results, threshMethod="Triangle", subtractBackground=True, watershed=True, minSize=0.00, maxSize=100, minCirc=0.00, maxCirc=1.00) # Settings for channel2 threshold. c2 = countobjects(channels[1], c2Results, threshMethod="RenyiEntropy", subtractBackground=True, watershed=False, minSize=0.00, maxSize=30.00, minCirc=0.00, maxCirc=1.00) # Settings for channel3 threshold. c3 = countobjects(channels[2], c3Results, threshMethod="RenyiEntropy", subtractBackground=True, watershed=False, minSize=0.00, maxSize=30.00, minCirc=0.00, maxCirc=1.00) # Settings for channel4 threshold. c4 = countobjects(channels[3], c4Results, threshMethod="RenyiEntropy", subtractBackground=True, watershed=False, minSize=0.20, maxSize=100.00, minCirc=0.00, maxCirc=1.00) # Format filenames for thresholded .tiff files. outfileC1 = os.path.join(c1dir, "threshold_c1_{}".format(name)) outfileC2 = os.path.join(c2dir, "threshold_c2_{}".format(name)) outfileC3 = os.path.join(c3dir, "threshold_c3_{}".format(name)) outfileC4 = os.path.join(c4dir, "threshold_c4_{}".format(name)) # Save thresholded .tiff files. IJ.saveAs(c1.flatten(), "Tiff", outfileC1) IJ.saveAs(c2.flatten(), "Tiff", outfileC2) IJ.saveAs(c3.flatten(), "Tiff", outfileC3) IJ.saveAs(c4.flatten(), "Tiff", outfileC4) # Show results tables. # c1Results.show("channel1") # c2Results.show("channel2") # c3Results.show("channel3") # c4Results.show("channel4") # Prepare results table filenames. c1out = os.path.join(outdir, "channel1.csv") c2out = os.path.join(outdir, "channel2.csv") c3out = os.path.join(outdir, "channel3.csv") c4out = os.path.join(outdir, "channel4.csv") # Save results tables. ResultsTable.save(c1Results, c1out) ResultsTable.save(c2Results, c2out) ResultsTable.save(c3Results, c3out) ResultsTable.save(c4Results, c4out)
sys.exit(str(trackmate.getErrorMessage())) # Display results of tracks on the image selectionModel = SelectionModel(model) displayer = HyperStackDisplayer(model, selectionModel, imp) displayer.render() displayer.refresh() #6. #get spot and track features # The feature model, that stores edge and track features. fm = model.getFeatureModel() for id in model.getTrackModel().trackIDs(True): model.getLogger().log('0.0,0.0,0.0,0.0') track = model.getTrackModel().trackSpots(id) for spot in track: # Fetch spot features directly from spot. x = spot.getFeature('POSITION_X') y = spot.getFeature('POSITION_Y') t = spot.getFeature('FRAME') mean = spot.getFeature('MEAN_INTENSITY') model.getLogger().log( str(t) + ',' + str(x) + ',' + str(y) + ',' + str(mean)) #7. #saving log as a txt file on desktop, then reading txt and rewriting as csv. IJ.selectWindow("Log") badname = image filename = badname.replace(".tif", "") IJ.saveAs("Text", filename + "_coordinates") IJ.run("Close")
def analyse(cwd, user, imagefolder, stats, experiments, multi, Rloc2, subfoldernames, names, statsfolderPath, cwdR): """ Main image analysis Gets user image analysis settings from the .csv file. If multiple experiments have been selected by the user (multi) each subfolder will be looped through. A nested loop will then interate through each .tif image and analyse. A .csv file will be produced for each folder analysed with the name of each image and its % neurite density and % myelination. A summary csv file will also be produced with the average % neurite density and % myelination for each subfolder. If statistical analysis has been selected (stats) then MyelinJ's Rscript will be run via the command line. If multple experiments is not selected then all of the images within the selected folder will be analysed together and no summary .csv will be produced. Independ of the analysis settings defined, a processed myelin channel image and a processed neurite channel image will be saved. The images can be any number of subdirectories (folders within folders). Parameters ---------- cwd : string Path for current working directory (location of MyelinJ folder in Fiji). user: string User name imagefolder: string Path to .tiff image folder(s) defined by user. stats: boolean Perform statistical analysing using R? experiments: 2D list of strings list of all the subfolders (experiments) that are in each experimental condition. multi: boolean Analyse multiple experiments? Rloc2: string file path to Rscript location subfoldernames: string name of each subfolder which denoates each individual experiment, if multple experiments are being analysed. names: array array of textfields for each experimental condition defined by user. User will enter the name of each experimental condition. statsfolderPath: string file path to the create statsfolder. cwdR: string file path to MyelinJstats.R """ # read settings from the user name CSV bg = False readsettings = [] imagenames = [] neuritedensity = [] myelinoverlay = [] myelinaverage2 = [] neuriteaverage2 = [] root = cwd filename = user fullpath = os.path.join(root, filename) f = open(fullpath, 'rb') readCSV = csv.reader(f) for row in readCSV: readsettings.append(row[0]) readsettings.append(row[1]) readsettings.append(row[2]) readsettings.append(row[3]) readsettings.append(row[4]) readsettings.append(row[5]) readsettings.append(row[6]) f.close() i = 0 for i in range(len(subfoldernames)): # if multiple experimental conditions has been selected each folder is treated as a # separate experiment and looped through separately otherwise all folders will be # treated as one experiment this only works for sub directories within the main folder. # Further folders will be ignored (each image can be in its own folder for example) if multi is True: # if multiple experiments are being analysed the file path is changed to the # current subfolder settings2 = os.path.join(imagefolder, subfoldernames[i]) if "Windows" in OS: settings2 = settings2 + "\\" elif "Mac" in OS: settings2 = settings2 + "/" else: settings2 = imagefolder # loop through all .tiff files in location for root, dirs, files in os.walk(settings2): for name in files: if name.endswith((".tif")): imagenames.append(os.path.join(name)) # open .tiff image, split channels and # convert to 8bit grey scale. imp = IJ.openImage(os.path.join(root, name)) g = int(readsettings[4]) r = int(readsettings[5]) imp = ChannelSplitter.split(imp) green = imp[g] red = imp[r] conv = ImageConverter(red) conv.convertToGray8() conv = ImageConverter(green) conv.convertToGray8() # thresholding to select cell bodies green2 = green.duplicate() if (readsettings[0] != "0") or (readsettings[1] != "0"): bg = True IJ.setAutoThreshold(green2, readsettings[2]) IJ.setRawThreshold(green2, int(readsettings[0]), int(readsettings[1]), None) Prefs.blackBackground = True IJ.run(green2, "Convert to Mask", "") IJ.run(green2, "Invert LUT", "") if readsettings[7] != "0": IJ.run(green2, "Make Binary", "") IJ.run( green2, "Remove Outliers...", "radius=" + readsettings[7] + " threshold=50 which=Dark") # CLAHE and background subtraction if readsettings[8] == "True": mpicbg.ij.clahe.Flat.getFastInstance().run( green, 127, 256, 3, None, False) if readsettings[9] == "True": calc = ImageCalculator() green = calc.run("Subtract create", green, red) elif readsettings[6] == "True": IJ.run(green, "Subtract Background...", "rolling=50") if readsettings[10] != "0": IJ.run(green, "Subtract...", "value=" + readsettings[10]) # run frangi vesselness pixelwidth = str(green.getCalibration().pixelWidth) IJ.run( green, "Frangi Vesselness (imglib, experimental)", "number=1 minimum=" + pixelwidth + " maximum=" + pixelwidth) green = IJ.getImage() # convert frangi vesselness image to 8bit grey scale conv = ImageConverter(green) conv.convertToGray8() IJ.run(green, "Convert to Mask", "") # remove cell bodies if bg is True: green = ImageCalculator().run("Subtract create", green, green2) # run grey scale morphology filter from MorpholibJ if readsettings[11] != "0": green = green.getProcessor() algo = BoxDiagonalOpeningQueue() algo.setConnectivity(4) result = algo.process(green, int(readsettings[11])) green = ImagePlus("result", result) IJ.run(green, "Invert LUT", "") if len(readsettings) > 14: # sparse neurite image analysis if readsettings[15] == "True": IJ.run( red, "Enhance Local Contrast (CLAHE)", "blocksize=127 histogram=256 maximum=3 mask=*None* fast_(less_accurate)" ) if readsettings[14] == "True": IJ.run(red, "Subtract Background...", "rolling=50") IJ.setAutoThreshold(red, readsettings[16]) IJ.setRawThreshold(red, int(readsettings[17]), int(readsettings[18]), None) IJ.run(red, "Convert to Mask", "") IJ.run(red, "Invert LUT", "") else: # dense neurite image analysis IJ.run( red, "Normalize Local Contrast", "block_radius_x=40 block_radius_y=40 standard_deviations=" + readsettings[12] + " center stretch") IJ.run(red, "Auto Threshold", "method=Default white") IJ.run(red, "Invert LUT", "") if readsettings[3] == "True": IJ.run(red, "Despeckle", "") IJ.saveAs(red, "Jpeg", settings2 + name + "neurites") # get number of neurite pixels # get number of neurite pixels statsneurite = red.getProcessor() statsneurite = statsneurite.getHistogram() neuritedensity.append(statsneurite[255]) IJ.saveAs(green, "Jpeg", settings2 + name + "myelinFinal") # get number of myelin pixels statsmyelin = green.getProcessor() statsmyelin = statsmyelin.getHistogram() myelinoverlay.append(statsmyelin[255]) closeallimages() # get pixel total of image whitepixels = (statsneurite[0]) blackpixels = (statsneurite[255]) totalpixels = whitepixels + blackpixels totalpixels = [totalpixels] * len(neuritedensity) # for each image calculate % myelination as number of myelin pixels # divided by the number of neurite pixels * 100 myelinoverlay = [ x1 / x2 * 100 for (x1, x2) in zip(myelinoverlay, neuritedensity) ] myelinaverage = sum(myelinoverlay) / len(myelinoverlay) myelinaverage2.append(myelinaverage) # for each image calculate % neurite density as neurite pixels divided # by the total number of pixels in the image * 100. neuritedensity = [ x1 / x2 * 100 for (x1, x2) in zip(neuritedensity, totalpixels) ] neuriteaverage = sum(neuritedensity) / len(neuritedensity) neuriteaverage2.append(neuriteaverage) name = "Image names" green = "% myelination" red = "% neurite density" imagenames = [name] + imagenames neuritedensity = [red] + neuritedensity myelinoverlay = [green] + myelinoverlay result = [] result.append(imagenames) result.append(neuritedensity) result.append(myelinoverlay) root = settings2 filename = "Results.csv" fullpath = os.path.join(root, filename) f = open(fullpath, 'wb') writer = csv.writer(f) for d in range(len(result)): row = [result[d]] writer.writerows(row) f.close() # must be reset to 0 for each iteration. y = 0 r = 0 # if statistical analysis is being performed the results .csv file # is also saved to a subfolder within the statistical analysis folder # which denotes the experimental condition the results belong to. if stats is True: # nested for loop to identify correct experimental condition # for the current subfolder being analysed. for y in range(0, len(experiments)): for r in range(0, len(experiments[0])): if experiments[y][r] == subfoldernames[i]: if "Windows" in OS: root = imagefolder + "\\statistical analysis\\" + names[ y].getText() elif "Mac" in OS: root = imagefolder + "/statistical analysis/" + names[ y].getText() filename = subfoldernames[i] + ".csv" fullpath = os.path.join(root, filename) f = open(fullpath, 'wb') writer = csv.writer(f) for e in range(len(result)): row = [result[e]] writer.writerows(row) f.close() break cwd2 = os.getcwd() for files in os.listdir(cwd2): if files.endswith(".csv"): os.remove(os.path.join(cwd2, files)) imagenames = [] myelinoverlay = [] neuritedensity = [] # create .csv summary sheet with average % neurite density # and average % myelination for each subfolder (experiment). if multi is True: name = "Folder name" imagenames = [name] + subfoldernames neuritedensity = [red] + neuriteaverage2 myelinoverlay = [green] + myelinaverage2 result = [] result.append(imagenames) result.append(neuritedensity) result.append(myelinoverlay) if "Windows" in OS: root = imagefolder + "\\" elif "Mac" in OS: root = imagefolder + "/" filename = "Result-Summary.csv" fullpath = os.path.join(root, filename) f = open(fullpath, 'wb') writer = csv.writer(f) for p in range(len(result)): row = [result[p]] writer.writerows(row) f.close() imagenames = [] myelinoverlay = [] neuritedensity = [] # Run Rscript for statistical analysis via the command line if stats is True: cmd = Rloc2 + " " + cwdR + " " + statsfolderPath Runtime.getRuntime().exec(cmd) Finished()
from ij import IJ from ij.plugin.frame import RoiManager from ij.gui import Roi # Get the active image, its title, and the directory where it lies imp = IJ.getImage() imp_title = imp.getTitle() path = IJ.getDirectory("image") IJ.log("Active image source: {}{}".format(path, imp_title)) # Set measurements to redirect to the active image IJ.run( "Set Measurements...", "area mean standard min center perimeter bounding fit feret's integrated median stack display redirect={}" .format(imp_title)) # Instantiate RoiManager as rm, select all rois and measure them roim = RoiManager.getInstance() roim.runCommand("Select All") roim.runCommand("Measure") # Save the measurements just made using the name of the active image measurements_filename = imp_title[:-4] IJ.saveAs("Results", "{}{}_background.csv".format(path, measurements_filename)) IJ.selectWindow("Results") IJ.run("Close") IJ.log("Measurements saved at {}{}.csv".format(path, measurements_filename))
def linear_blending(aurox_dir_path, current_dirs, c_ome_path, yes_orig): """ Linear blend images. It saves two images: A fused tiff from TileConfiguration.fixed.txt with Z axis set to 0, saved into FUSED_TIFFS and a separate fused tiff from TileConfiguration.txt with original positions from positions.csv file, saved into ORIG_FUSED_TIFFS """ fusloc_dict = {} abs_dirpath = os.path.abspath(aurox_dir_path) prefix = os.path.basename(aurox_dir_path) sav_fu = "%s/%s.tiff" % (current_dirs[0], prefix) sav_orig = "%s/%s.orig.tiff" % (current_dirs[3], prefix) # Creates both images if 'Create image from original positions?' was # checked. if yes_orig: # Linear Blending IJ.run("Grid/Collection stitching", "type=[Positions from file] " "order=[Defined by TileConfiguration]" " directory=[%s] layout_file=TileConfiguration.fixed.txt " "fusion_method=[Linear Blending] " "regression_threshold=0.30 max/avg_displacement_threshold=2.50 " "absolute_displacement_threshold=3.50 " "computation_parameters=[Save computation time (but use more RAM)] " "image_output=[Fuse and display]" % abs_dirpath) IJ.saveAs("Tiff", sav_fu) IJ.run("Close All") # Linear Blending IJ.run("Grid/Collection stitching", "type=[Positions from file] " "order=[Defined by TileConfiguration] " "directory=[%s] layout_file=TileConfiguration.txt " "fusion_method=[Linear Blending] " "regression_threshold=0.30 max/avg_displacement_threshold=2.50 " "absolute_displacement_threshold=3.50 " "computation_parameters=[Save computation time (but use more RAM)] " "image_output=[Fuse and display]" % abs_dirpath) IJ.saveAs("Tiff", sav_orig) IJ.run("Close All") # Creates only a single image with the calculated overlap and new positions else: # Linear Blending IJ.run("Grid/Collection stitching", "type=[Positions from file] " "order=[Defined by TileConfiguration] " "directory=[%s] layout_file=TileConfiguration.fixed.txt " "fusion_method=[Linear Blending] " "regression_threshold=0.30 max/avg_displacement_threshold=2.50 " "absolute_displacement_threshold=3.50 " "computation_parameters=[Save computation time (but use more RAM)] " "image_output=[Fuse and display]" % abs_dirpath) IJ.saveAs("Tiff", sav_fu) IJ.run("Close All") fusloc_dict[sav_fu] = [c_ome_path, current_dirs[1]] return fusloc_dict
name = imp.getTitle()[0:2] if not name.isdigit(): name = imp.getTitle()[0:1] #name = int(''.join(filter(str.isdigit, name))) IJ.run("Select All") IJ.run("Duplicate...", "check and close") newimp = IJ.getImage() rm.runCommand(newimp, "Show All") if rm.getCount() > 1: rm.setSelectedIndexes(range(rm.getCount())) rm.runCommand(newimp, "Combine") else: rm.select(newimp, 0) IJ.run("Make Inverse") IJ.run("Cut") gd = GenericDialog("suffix") gd.addStringField("suffix:", "") gd.showDialog() suffix = gd.getNextString() #ync = YesNoCancelDialog(None, "intensity (yes) or coverage (no or cancel)", "intensity (yes) or coverage (no or cancel)"); #if ync.yesPressed(): IJ.saveAs("Tiff", path + "\\prepared\\" + name + suffix + ".tif") #rm.runCommand("Delete") #else: #IJ.saveAs("Tiff", path + "\\coverage\\" + name + suffix + ".tif"); #IJ.saveAs("Tiff", path + "\\MTs\\prepared\\" + name + suffix + ".tif"); #IJ.run("Undo"); #ij.RUN("mAKE iNVERSE"); #ij.RUN("cUT"); #ij.SAVEaS("tIFF", PATH + "PREPARED\\" + NAME + "P.TIF"); #rm.runCommand("Save", path + "\\MTs\\prepared\\" + name + suffix + ".zip")
#print current_patch[0].getImageFilePath() ip = Patch.makeFlatImage(ImagePlus.COLOR_RGB, layer, rectangle, scale, current_patch, backgroundColor, True) # use the min and max of each tile imp = ImagePlus("img", ip) imp2 = imp.flatten() ip2 = Patch.makeFlatImage(ImagePlus.COLOR_RGB, layer, rectangle, scalesmall, current_patch, backgroundColor, True) # use the min and max of each tile imp3 = ImagePlus("img", ip2) imp4 = imp3.flatten() #imp2.show() if patch_num == 0: IJ.saveAs(imp2, "PNG", (exp_folder + "elastic_align/storm_merged/" + basename[:-4] + ".png")) IJ.saveAs(imp4, "PNG", (exp_folder + "elastic_align/storm_merged_ds/" + basename[:-4] + ".png")) if patch_num == 1: IJ.saveAs(imp2, "PNG", (exp_folder + "elastic_align/conv_merged/" + basename[:-4] + ".png")) IJ.saveAs(imp4, "PNG", (exp_folder + "elastic_align/conv_merged_ds/" + basename[:-4] + ".png")) IJ.run("Close All", "") if patch_num == 2: IJ.run(imp2, "8-bit", "") IJ.saveAs(imp2, "PNG", (exp_folder + "elastic_align/conv_561/" +
# asks if you have selected anything try: roi_points = overlay.toArray() except AttributeError as error: nbgd = NonBlockingGenericDialog("Select some cells boi") nbgd.showDialog() if blur_state == True: set_sigma = "sigma=" + str(blur_val) + " stack" IJ.run("Gaussian Blur...", set_sigma) path = os.chdir(dest) if not os.path.exists(ProFolder): os.mkdir(ProFolder) os.chdir(ProFolder) Path = (os.getcwd()) IJ.run("Copy to System") IJ.saveAs('Tiff', os.path.join(Path, Save_Title)) else: os.chdir(ProFolder) Path = (os.getcwd()) IJ.run("Copy to System") IJ.saveAs('Tiff', os.path.join(Path, Save_Title)) fret_csv = Path + '/' + Procsv if back_state == False: imp.setRoi(roi_bck) background_c1, background_c2 = background_assay() all_x = [] all_y = [] for i in range(overlay.size()):
strName = os.path.basename(fi) strName = strName.split('.')[0] lStr = strName.split('-') l = len(lStr) strNum = lStr[l-1] iNum = int(strNum) orig.setTitle(strNum) cal = orig.getCalibration() strUnit = cal.getUnit() if strUnit == "micron": mu = IJ.micronSymbol strUnit = mu + "m" cal.setUnit(strUnit) orig.setCalibration(cal) orig.updateAndRepaintWindow() # IJ.run(orig, "Enhance Contrast", "saturated=0.35") IJ.run(orig, "16-bit", "") orig.show() outPth = sTifPath + strName + ".tif" IJ.saveAs(orig, "Tiff", outPth) time.sleep(1) orig.close() toc = time.time() elapsed = toc - tic print("analyzed %g images" % i) print("completed in %g sec" % elapsed )
from ij import IJ from ij.plugin import ImageCalculator IJ.run("Close All") path_tif = "/Users/jrminter/Documents/git/tips/ImageJ/tif/lena-eyes.tif" path_jpg = "/Users/jrminter/Documents/git/tips/ImageJ/jpg/lena-eyes.jpg" lena_tif = IJ.openImage(path_tif) lena_tif.show() IJ.saveAs(lena_tif, "Jpeg", path_jpg) for i in range(201): lena_jpg = IJ.openImage(path_jpg) IJ.saveAs(lena_jpg, "Jpeg", path_jpg) IJ.run(lena_jpg, "32-bit", "") IJ.run(lena_tif, "32-bit", "") lena_tif.show() lena_jpg.show() ic = ImageCalculator() imp_sub = ic.run("Subtract create 32-bit", lena_jpg, lena_tif) IJ.run(imp_sub, "Enhance Contrast", "saturated=0.35") IJ.run(imp_sub, "8-bit", "") imp_sub.show()
""" make_mandrill_256.py Make a cropped Mandrill Image Date Who What ---------- --- ---------------------------------------------------- 2019-06-16 JRM Initial adaptation. Use the HOME environment variable to get the start of the path """ from ij import IJ import os home_dir = os.getenv("HOME") print(home_dir) IJ.run("Close All") imp = IJ.openImage(home_dir + "/dat/images/key-test/mandrill.tif"); imp.setRoi(0,0,256,256); imp.show() IJ.run("Crop") imp.show() IJ.saveAs(imp, "Tiff", home_dir + "/Documents/git/tips/ImageJ/tif/mandrill_256.tif");
from ij.io import OpenDialog import os from ij.measure import ResultsTable IJ.run("Clear Results") #clear results od = OpenDialog("Choose a file", None) filename = od.getFileName() directory = od.getDirectory() path = od.getPath() print filename print directory print path imp = IJ.openImage(path) imp.show() #imp = IJ.getImage() IJ.run("8-bit") IJ.run("Invert") #use this line if we need to invert the image IJ.run("Set Measurements...", "area min redirect=None decimal=3") IJ.run("Analyze Particles...", "display") #save the results table as a CSV #https://www.ini.uzh.ch/~acardona/fiji-tutorial/#s2 save_string = directory + 'Results_random_circles_CoronaTime.csv' IJ.saveAs("Results", save_string) #table = ResultsTable.getResultsTable()
for i in range(len(x)): x[i] = float(x[i]) * dimensions y = coordinates[2]; for i in range(len(y)): y[i] = float(y[i]) * dimensions m = coordinates[3]; for i in range(len(m)): m[i] = float(m[i]) #3. rm = RoiManager.getInstance() #prompt Set Measurements GUI IJ.run("Set Measurements...") if (rm==None): rm = RoiManager() for i in range(len(t)): if x[i] != 0: #imp.setPosition switches to GFP channel and sets frame for each ROI imp.setPosition(2, 1, int(t[i])+1) #adds an oval ROI centered around coordinates rm.addRoi(ij.gui.OvalRoi(x[i]-5, y[i]-5, 10, 10)) #measures requested data on all ROIs rm.runCommand(imp,"Measure") #4. Saving measured data to desktop IJ.selectWindow("Results") IJ.saveAs("Text", filename+"_results") IJ.run("Close")
imp = IJ.openImage((ISanalysisfolder + "%04d" % i + "/aligned/after_dist_corr/488storm_" + "%03d" % i + "_" + "%02d" % j + "_0.tif")) imp.show() IJ.run(imp, "Canvas Size...", "width=2350 height=2350 position=Center zero"); IJ.run(imp, "Canvas Size...", "width=2560 height=2560 position=Center zero"); #imp = IJ.openImage((ISanalysisfolder + "%04d" % i + "/aligned/after_dist_corr/488storm_" + "%03d" % i + "_" + "%02d" % j + "_1.tif")) imp = IJ.openImage((ISanalysisfolder + "%04d" % i + "/aligned/after_dist_corr/488storm_" + "%03d" % i + "_" + "%02d" % j + "_0.tif")) imp.show() IJ.run(imp, "Canvas Size...", "width=2350 height=2350 position=Center zero"); IJ.run(imp, "Canvas Size...", "width=2560 height=2560 position=Center zero"); IJ.run(imp, "Images to Stack", "name=Stack title=[] use"); imp = IJ.getImage() IJ.run(imp, "Z Project...", "start=1 stop=2 projection=[Average Intensity]"); imp = IJ.getImage() else: imp = IJ.createImage("Untitled", "8-bit Black", 2560, 2560, 1); IJ.saveAs(imp, "Tiff", (ISanalysisfolder + "%04d" % i + "/aligned/488storm_" + "%03d" % i + "_" + "%02d" % j + ".tif")); IJ.run("Close All", ""); #if os.path.isfile((ISanalysisfolder + "%04d" % i + "/aligned/after_dist_corr/561storm_" + "%02d" % i + "_" + "%02d" % j + "_0.tif")): # imp = IJ.openImage((ISanalysisfolder + "%04d" % i + "/aligned/after_dist_corr/561storm_" + "%02d" % i + "_" + "%02d" % j + "_0.tif")) # imp.show() # IJ.run(imp, "Canvas Size...", "width=2350 height=2350 position=Center zero"); # IJ.run(imp, "Canvas Size...", "width=2560 height=2560 position=Center zero"); # imp = IJ.openImage((ISanalysisfolder + "%04d" % i + "/aligned/after_dist_corr/561storm_" + "%02d" % i + "_" + "%02d" % j + "_1.tif")) # imp.show() # IJ.run(imp, "Canvas Size...", "width=2350 height=2350 position=Center zero"); # IJ.run(imp, "Canvas Size...", "width=2560 height=2560 position=Center zero"); # IJ.run(imp, "Images to Stack", "name=Stack title=[] use"); # imp = IJ.getImage() # IJ.run(imp, "Z Project...", "start=1 stop=2 projection=[Average Intensity]"); # imp = IJ.getImage()
# import the source code for ImageJ from ij import IJ from ij import plugin from ij import WindowManager as wm # get image object imp_all = IJ.getImage() # print the base name of the file imp_basename = imp_all.title.replace(".nd2", "") print(imp_basename) # return the info for image # No need to have image object in the arguments IJ.run("Show Info...") # select the info window img_info = wm.getActiveWindow() # return the title of the window (optional) print(img_info.title) # save the info information IJ.saveAs("Text", metadata + imp_basename + ".txt") # close the window img_info.close()
def batch_open_images(pathImage, pathRoi, pathMask, file_typeImage=None, name_filterImage=None, recursive=False): '''Open all files in the given folder. :param path: The path from were to open the images. String and java.io.File are allowed. :param file_type: Only accept files with the given extension (default: None). :param name_filter: Only accept files that contain the given string (default: None). :param recursive: Process directories recursively (default: False). ''' # Converting a File object to a string. if isinstance(pathImage, File): pathImage = pathImage.getAbsolutePath() def check_type(string): '''This function is used to check the file type. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the check on. ''' if file_typeImage: # The first branch is used if file_type is a list or a tuple. if isinstance(file_typeImage, (list, tuple)): for file_type_ in file_typeImage: if string.endswith(file_type_): # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if file_type is a string. elif isinstance(file_typeImage, string): if string.endswith(file_typeImage): return True else: return False return False # Accept all files if file_type is None. else: return True def check_filter(string): '''This function is used to check for a given filter. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the filtering on. ''' if name_filterImage: # The first branch is used if name_filter is a list or a tuple. if isinstance(name_filterImage, (list, tuple)): for name_filter_ in name_filterImage: if name_filter_ in string: # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if name_filter is a string. elif isinstance(name_filterImage, string): if name_filterImage in string: return True else: return False return False else: # Accept all files if name_filter is None. return True # We collect all files to open in a list. path_to_Image = [] # Replacing some abbreviations (e.g. $HOME on Linux). path = os.path.expanduser(pathImage) path = os.path.expandvars(pathImage) # If we don't want a recursive search, we can use os.listdir(). if not recursive: for file_name in os.listdir(pathImage): full_path = os.path.join(pathImage, file_name) if os.path.isfile(full_path): if check_type(file_name): if check_filter(file_name): path_to_Image.append(full_path) # For a recursive search os.walk() is used. else: # os.walk() is iterable. # Each iteration of the for loop processes a different directory. # the first return value represents the current directory. # The second return value is a list of included directories. # The third return value is a list of included files. for directory, dir_names, file_names in os.walk(pathImage): # We are only interested in files. for file_name in file_names: # The list contains only the file names. # The full path needs to be reconstructed. full_path = os.path.join(directory, file_name) # Both checks are performed to filter the files. if check_type(file_name): if check_filter(file_name) is False: # Add the file to the list of images to open. path_to_Image.append([full_path, os.path.basename(os.path.splitext(full_path)[0])]) # Create the list that will be returned by this function. Images = [] Rois = [] for img_path, file_name in path_to_Image: # IJ.openImage() returns an ImagePlus object or None. imp = IJ.openImage(img_path) print(img_path) if check_filter(file_name): continue; else: print(file_name , pathRoi) RoiName = str(pathRoi) + '/'+ file_name + '.roi' Roi = IJ.open(RoiName) # An object equals True and None equals False. rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.addRoi(Roi) impMask = IJ.createImage("Mask", "8-bit grayscale-mode", imp.getWidth(), imp.getHeight(), imp.getNChannels(), imp.getNSlices(), imp.getNFrames()) IJ.setForegroundColor(255, 255, 255) rm.runCommand(impMask,"Deselect") rm.runCommand(impMask,"Fill") rm.runCommand('Delete') IJ.saveAs(impMask, '.tif', str(pathMask) + "/" + file_name); imp.close(); #print(img_path, RoiName) Images.append(imp) Rois.append(Roi) return Images, Rois
def doInBackground(self): try: # In case there is an error, so that FIJI doesn't crash print "INICIO" print self.files print self.pix_erosion_mult label_files = [f for f in self.files if f.endswith('_label.png') or f.endswith('_label.tif') or f.endswith('_label.jpg')] total_label_files = len(label_files) print "total label files:" print total_label_files gvars["total label files"] = total_label_files for filenum, f in enumerate(label_files): # Loop through the files in the directory self.label_update(filenum+1, total_label_files) label_file = f print "----" print label_file original_name = re.sub(r"_label.*", "",f) # get name of the original image without extension if (original_name+".tif") in self.files: # for an original image with extension .tif original_file = original_name+".tif" print original_file elif (original_name+".tiff") in self.files: # for an original image with extension .tiff (with double f) original_file = original_name+".tiff" print original_file else: # If there is no original image original_file = "None" print original_file path_multiple = gvars['path_multiple_image_directory'] print path_multiple ########### Section Label To Roi ########### RM = RoiManager() rm = RM.getRoiManager() label_image = IJ.openImage(path_multiple + "\\" + label_file) rm.reset() rm.runCommand(label_image,"Show All without labels") # we make sure we see the ROIs as they are loading imp2 = label_image.duplicate() ip = imp2.getProcessor() width = imp2.getWidth() height = imp2.getHeight() - 1 max_label = int(imp2.getStatistics().max) max_digits = int(math.ceil(math.log(max_label,10))) # Calculate the number of digits for the name of the ROI (padding with zeros) IJ.setForegroundColor(0, 0, 0) # We pick black color to delete the label already computed for j in range(height): for i in range(width): current_pixel_value = ip.getValue(i,j) if current_pixel_value > 0: IJ.doWand(imp2, i, j, 0.0, "Legacy smooth"); # We add this ROI to the ROI manager roi = imp2.getRoi() roi.setName(str(int(current_pixel_value)).zfill(max_digits)) rm.addRoi(roi) ip.fill(roi) # Much faster than IJ.run(imp2, "Fill", .... # Update ProgressBar progress = int((current_pixel_value / max_label) * 100) self.super__setProgress(progress) rm.runCommand(label_image,"Sort") # Sort the ROIs in the ROI manager rm.runCommand(label_image,"Show All without labels") ######### Section ROI erotion ######### for i in range(0, rm.getCount()): roi = rm.getRoi(i) new_roi = RoiEnlarger.enlarge(roi, -self.pix_erosion_mult) # Important to use this instead of the IJ.run("Enlarge... much faster!! rm.setRoi(new_roi,i) ####### Section Save ROIs ############## print original_name path_to_multiple_ROIs = str(gvars['path_multiple_image_directory']) + "\\" + original_name + "_Erosion_" +str(self.pix_erosion_mult)+ "px_" + "RoiSet.zip" print path_to_multiple_ROIs rm.runCommand("Save", path_to_multiple_ROIs) print("ROIs saved") ####### Section open Original Image ############## if original_file != "None": # If there is an original image file besides the label image, we'll measure and generate table of measurements print "There is an original image associated to this label" original_image = IJ.openImage(path_multiple + "\\" + original_file) IJ.run(original_image, "Enhance Contrast", "saturated=0.35") rm.runCommand(original_image,"Show All without labels") #original_image.show() table_message = [] is_scaled = original_image.getCalibration().scaled() if is_scaled: spatial_cal = "True" else: spatial_cal = "False" nChannels = original_image.getNChannels() print "Total channels:" print nChannels for current_channel in range(1,nChannels+1): print "Current channel:" print current_channel original_image.setSlice(current_channel) current_slice = str(original_image.getCurrentSlice()) #Get current slice for saving into filename print "Current slice:" print current_slice IJ.run("Clear Results", "") rm.runCommand(original_image,"Select All"); rm.runCommand(original_image,"Measure") table = ResultsTable.getResultsTable().clone() IJ.selectWindow("Results") IJ.run("Close") for i in range(0, table.size()): table.setValue('File', i, str(original_name)) table.setValue('Channel', i, current_channel) table.setValue('Pixels_eroded', i, str(self.pix_erosion_mult)) table.setValue('Spatial_calibration', i, spatial_cal) table.show("Tabla actualizada") path_to_multiple_Tables = str(gvars['path_multiple_image_directory']) + "\\" + original_name + "_Erosion_" +str(self.pix_erosion_mult)+ "px_Channel_" + str(current_channel) + ".csv" IJ.saveAs("Results", path_to_multiple_Tables) # Section Save jpg with outlines path_to_multiple_outline = str(gvars['path_multiple_image_directory']) + "\\" + original_name + "_Erosion_" +str(self.pix_erosion_mult)+ "px_" + "Outlines.jpg" outlines_image = original_image.flatten() IJ.saveAs(outlines_image, "JPG", path_to_multiple_outline) IJ.run("Close") else: print "There is NOT an original image associated to this label" label_image.close() ####### Section ending ############## except Exception as e: print e
for y in range(int(rows)): out_name = thisprefix + '_Well_' + eachwell + '_x_' + '%02d' % x + '_y_' + '%02d' % y + '_' + thissuffix if (x, y) in filled_positions: series = pos_dict[(x, y)] in_name = thisprefix + '_Well_' + eachwell + '_Site_' + str( series) + '_' + thissuffix IJ.open(os.path.join(subdir, in_name)) else: IJ.newImage("Untitled", "16-bit noise", int(size), int(size), 1) IJ.run( "Divide...", "value=300" ) #get the noise value below the real camera noise level emptylist.append(out_name) im = IJ.getImage() IJ.saveAs(im, 'tiff', os.path.join(subdir, out_name)) IJ.run("Close All") if (x, y) in filled_positions: try: #try to clean up after yourself, but don't die if you can't os.remove(os.path.join(subdir, in_name)) except: pass print("Renamed all files for prefix " + thisprefix + " and suffix " + thissuffix + " in well " + eachwell) imagelist = os.listdir(subdir) print(len(imagelist), 'files in subdir') print(imagelist[:10]) #top left quarter print('Running top left') #Change per quarter standard_grid_instructions = [
#@File(label="first file of the input sequence with the reconstructed 16 bit data") input_file #@File(label="first file of the output sequence with the segmented data") output_file from ij import IJ print "opening", input_file IJ.run("Image Sequence...", "open=%s sort" % input_file) print "geometry to distance map" IJ.run("Geometry to Distance Map", "threshold=128") # print "distance map to distance ridge" # IJ.run("Distance Map to Distance Ridge") print "save to", output_file IJ.saveAs("Raw Data", "%s" % output_file) IJ.run("Quit")
IJ.run("3D OC Options", params) params = ("threshold=" + str(intThreshold) + " slice=1 min.=" + str(sizeThreshold) + " max.=24903680 objects surfaces statistics") IJ.redirectErrorMessages(True) IJ.run(dataImage, "3D Objects Counter", params) dataImage.changes = False dataImage.close() ## Saves the results table, surfaces image output, and run configuration surfacesImage = WindowManager.getImage("Surface map of " + dataImage.getTitle()) IJ.run(surfacesImage,"8-bit","") surfacesImage = make_image_binary(surfacesImage) IJ.saveAsTiff(surfacesImage,parentLSMFilePath + "_tiles/surfaces/C" + str(analysisChannel) + "-tile_" + str(tile) + ".tif") surfacesImage.close() objectsImage = WindowManager.getImage("Objects map of " + dataImage.getTitle()) IJ.run(objectsImage,"8-bit","") objectsImage = make_image_binary(objectsImage) IJ.saveAsTiff(objectsImage,parentLSMFilePath + "_tiles/maps/C" + str(analysisChannel) + "-tile_" + str(tile) + ".tif") objectsImage.close() IJ.selectWindow("Results") IJ.saveAs("Results",parentLSMFilePath + "_tiles/objects/C" + str(analysisChannel) + "-tile_" + str(tile) + ".csv") configData = ("Parent LSM file: " + parentLSMFilePath + "\n" + "Analysis channel: " + str(analysisChannel) + "\n" + "Bleeding channel: " + str(bleedingChannel) + "\n" + "Refractive correction reference channel: " + str(refChannel) + "\n" + "Intensity threshold (0-255): " + str(intThreshold) + "\n" + "Size threshold (voxels): " + str(sizeThreshold) + "\n" + "Process filter: " + str(processFilter) + "\n" + "Tiles: " + ','.join([str(i) for i in tileList])) IJ.saveString(configData,parentLSMFilePath+"_tiles/objects/runData-C" + str(analysisChannel) + ".txt")
image = IJ.createImage('Download arrow', 'rgb', w, h, 1) ip = image.getProcessor() ip.setLineWidth(lineWidth) ip.setColor(Color(0x65a4e3)) roi = ShapeRoi([PathIterator.SEG_MOVETO, 0, 0, PathIterator.SEG_LINETO, w, 0, PathIterator.SEG_LINETO, w, w, PathIterator.SEG_LINETO, 0, w, PathIterator.SEG_CLOSE]) lw = lineWidth roi = roi.not(ShapeRoi([PathIterator.SEG_MOVETO, lw, lw, PathIterator.SEG_LINETO, w - lw, lw, PathIterator.SEG_LINETO, w - lw, w - lw, PathIterator.SEG_LINETO, lw, w - lw, PathIterator.SEG_CLOSE])) x1 = (w - arrowWidth) / 2 x2 = (w + arrowWidth) / 2 y1 = w * 2 / 3 roi = roi.or(ShapeRoi([PathIterator.SEG_MOVETO, x1, 0, PathIterator.SEG_LINETO, x1, y1, PathIterator.SEG_LINETO, 0, y1, PathIterator.SEG_LINETO, w / 2 - 1, h, PathIterator.SEG_LINETO, w / 2, h, PathIterator.SEG_LINETO, w - 1, y1, PathIterator.SEG_LINETO, x2, y1, PathIterator.SEG_LINETO, x2, 0, PathIterator.SEG_CLOSE])) ip.fill(roi) IJ.saveAs(image, "PNG", "resources/download-arrow.png")
inImg = impOut # Note: this returns a duplicate impOut = jmg.labelMontage(impOut, lAnn, nCol, nRow, w0=12, h0=2, font=24, col=Color.WHITE, bHeadless=bHeadless) impOut.setTitle(sampID + "-" + mapID) # show the annotated image if bHeadless != True: impOut.show() # burn a scale bar if sbPtX == None: strSB = "width=%g height=%g font=%g color=%s location=[Lower Right] bold" % (sbW, sbH, sbFont, sbCol ) else: impOut.setRoi(PointRoi(sbPtX, sbPtY)) strSB = "width=%g height=%g font=%g color=%s location=[At Selection] bold" % (sbW, sbH, sbFont, sbCol ) # first burn a scale bar in the original image to make sure changes are written IJ.run(inImg, "Add Scale Bar", strSB) # close the original inImg.changes = False inImg.close() # now burn the scale bar we really want... IJ.run(impOut, "Add Scale Bar", strSB) # impOut.setTitle(sampID + "-" + mapID) impOut.setRoi(PointRoi(-10, -10)) if bHeadless != True: impOut.updateAndRepaintWindow() IJ.saveAs(impOut, "PNG", outPth) if bHeadless: print("done")
input_image_plus = IJ.openImage( input ) # Create a copy of the image. input_image_plus_copy = input_image_plus.duplicate() image_processor_copy = input_image_plus_copy.getProcessor() try: # Convert image to binary if necessary. if not image_processor_copy.isBinary(): # Convert the image to binary grayscale. IJ.run( input_image_plus_copy, "Make Binary","iterations=1 count=1 edm=Overwrite do=Nothing" ) # Set the options. if jython_utils.asbool( dark_background ): method_str = "%s dark" % method else: method_str = method IJ.setAutoThreshold( input_image_plus_copy, method_str ) if display == "red": display_mode = "Red" elif display == "bw": display_mode = "Black & White" elif display == "over_under": display_mode = "Over/Under" IJ.setThreshold( input_image_plus_copy, threshold_min, threshold_max, display_mode ) # Run the command. IJ.run( input_image_plus_copy, "threshold", "" ) # Save the ImagePlus object as a new image. IJ.saveAs( input_image_plus_copy, output_datatype, tmp_output_path ) except Exception, e: jython_utils.handle_error( error_log, str( e ) )
ecd = 2.0*sqrt(lArea[j]/3.1415926) ecdOut.append(ecd) con = 1.0-(lMode[j]/iZero) conOut.append(con) cirOut.append(lCirc[j]) arOut.append(lAspRat[j]) rndOut.append(lRound[j]) solOut.append(lSolid[j]) orig.show() outPth = sRptImgPath + strName + ".png" # burn a scale bar and save the image IJ.run(orig, "RGB Color", "") IJ.run(orig, "Add Scale Bar", strBar) IJ.saveAs(orig, "PNG", outPth) orig.changes = False orig.close() print("%d particles detected in image %s" % (nMeas, strNum)) # prepare the output file f=open(sRptCsvPath, 'w') strLine = 'img, part, ecd.nm, contrast, circ, a.r, round, solidity\n' f.write(strLine) for k in range(len(ecdOut)): strLine = "%d, %d, %.2f, %.4f, %.4f, %.4f, %.4f, %.4f\n" % (imgOut[k], parOut[k], ecdOut[k], conOut[k], cirOut[k], arOut[k], rndOut[k], solOut[k] ) f.write(strLine) f.close()
import glob, os __author__ = 'Nichole Wespe' inputDir = IJ.getDirectory("Choose Source Directory ") outputDir = IJ.getDirectory("Choose Destination Directory ") for d in os.listdir(inputDir): strain = os.path.basename(os.path.normpath(d)).split("_") pattern = os.path.join(inputDir, d, "*.tif") print pattern fileList = glob.glob(pattern) print "Found " + str(len(fileList)) + " microscopy files to analyze." if len(fileList) == 0: continue n=0 for f in fileList: date, sample, strain, condition = os.path.basename(f).split("_") date = str(date) path = os.path.join(outputDir, sample) condition = condition.rstrip(".jpg") print date + " " + sample + " " + condition args = "date=[" + date + "] sample=[" + sample + "] strain =[" + strain + "] condition=[" + condition + \ "] file=[" + f + "] path=[" + path + "] number=[" + n + "]" Macro.setOptions(Thread.currentThread(), args) IJ.run("detect buds", args) n += 1 IJ.saveAs("Results", outputDir + "/" + strain + "_results.csv") IJ.selectWindow("Results") IJ.run("Close")
# - commands generally do not work on the active image but need a imp (ImagePlus) object to operate on. from ij import IJ; from ij import Prefs; # Get input from user #@File image (label="input image") #@File (style="directory", label="output directory") outputDirectory # Open image IJ.run("Close All"); imp = IJ.openImage( str(image) ); title = imp.getTitle(); # Binarize (Threshold) IJ.setRawThreshold(imp, 24, 255, None); Prefs.blackBackground = True; IJ.run(imp, "Convert to Mask", ""); # Connected components IJ.run(imp, "Connected Components Labeling", "connectivity=4 type=[16 bits]"); # Measure shape IJ.run("Region Morphometry"); # Export results IJ.saveAs("Results", str(outputDirectory) + "/" + title + ".csv"); # Clean up IJ.run("Close All");
def process(srcDir, dstDir, currentDir, fileName): print "\nProcessing:" # Open the image print "Opening image file", fileName imp = IJ.openImage(os.path.join(currentDir, fileName)) imp.show() # Run ComDet with specified parameters print "Running ComDet with " + "Approximate spot size: " + str(spot_size) + ", Intensity threshold: " + str(intensity_thresh) IJ.run("Detect Particles", "include ch1a=" + str(spot_size) + " ch1s=" + str(intensity_thresh) + " add=Nothing") print "Analyzing data" # Process results table rs = ResultsTable.getResultsTable() # Find intensity of 4th brightest spot intensityColIndex = rs.getColumnIndex(intensityCol) intensities = sorted(rs.getColumnAsDoubles(intensityColIndex), reverse=True) if (rs.size() > 4): # spots detected (excluding markers) markerIntensityThresh = intensities[3] # Calculate min, max, mean for all spots except those classified as markers # (can have more than 4 markers in case of ties) N = 0 mean = 0 minimum = float('Inf') maximum = -minimum for intensity in intensities: if intensity < markerIntensityThresh: mean += intensity N += 1 minimum = min(minimum, intensity) maximum = max(maximum, intensity) mean = mean/N # Calculate median across spots except those classified as markers intensities = sorted(intensities) if (math.fmod(N, 2) == 0): median = (intensities[int(N/2) - 1] + intensities[int(N/2)]) / 2 # indices start at 0 else: median = intensities[int(math.floor(N/2))] # Calculate variance, SD, CoV for all spots except those classified as markers # (can have more than 4 markers in case of ties) var = 0 for intensity in intensities: if intensity < markerIntensityThresh: var += (intensity - mean)**2 var = var/(N - 1) sd = math.sqrt(var) CoV = (sd/mean)*100 # coefficient of variation else: # only markers/nothing detected markerIntensityThresh = 0 N = 0 minimum = maximum = mean = median = var = sd = CoV = "n/a" print "Count: ", str(N), ", Min: ", str(minimum), ", Max: ", str(maximum), ", Mean: ", str(mean), ", Median: ", str(median), ", Variance: ", str(var), ", SD: ", str(sd), ", CoV: ", str(CoV) stats = [fileName.replace(ext, ""), str(N), str(minimum), str(maximum), str(mean), str(median), str(var), str(sd), str(CoV)] # Write results to csv csvDir = os.path.join(dstDir, "Intensity Results") if not os.path.exists(csvDir): os.makedirs(csvDir) csvFilename = os.path.join(csvDir, fileName.replace(ext, "") + ".csv") with open(csvFilename, 'wb') as csvfile: w = csv.writer(csvfile, delimiter=',') # Write summary to csv w.writerow(["Summary (marker spots excluded from analysis)"]) w.writerow(["Count", str(N)]) w.writerow(["Min IntegratedInt", str(minimum)]) w.writerow(["Max IntegratedInt", str(maximum)]) w.writerow(["Mean IntegratedInt", str(mean)]) w.writerow(["Median IntegratedInt", str(median)]) w.writerow(["Variance IntegratedInt", str(var)]) w.writerow(["SD IntegratedInt", str(sd)]) w.writerow(["CoV (%) IntegratedInt", str(CoV)]) # Blank line w.writerow([""]) # Write data to csv desiredCols.append("Marker Spot?") w.writerow(desiredCols) for row in range(rs.size()): line = [] for col in range(rs.getLastColumn() + 1): marker = False currColName = rs.getColumnHeading(col) if currColName in desiredCols: line.append(rs.getStringValue(col, row)) if currColName == intensityCol: # Check if spot is a marker spot if rs.getValueAsDouble(col, row) >= markerIntensityThresh: marker = True if (marker == True): line.append("Yes") else: line.append("") w.writerow(line) # Save the image saveDir = dstDir if not os.path.exists(saveDir): os.makedirs(saveDir) print "Saving to", saveDir IJ.saveAs(imp, saveExt.lower(), os.path.join(saveDir, fileName)) # Close the image imp.close() return stats
def processImages(cfg, wellName, wellPath, c, imgFiles): points = [] chanStr = 'ch%(channel)02d' % { "channel": c } chanName = cfg.getValue(ELMConfig.chanLabel)[c] if (chanName == ELMConfig.RED): chanPixBand = 0 elif (chanName == ELMConfig.GREEN): chanPixBand = 1 elif (chanName == ELMConfig.BLUE): chanPixBand = 2 elif (chanName == ELMConfig.YELLOW): chanPixBand = 0 else: chanPixBand = -1 chanPixBand numExclusionPts = 0 numColorThreshPts = 0 ptCount = 0 print "\tProcessing channel: " + chanName for t in range(cfg.getValue(ELMConfig.numT)): tStr = cfg.getTStr(t) for z in range(0, cfg.getValue(ELMConfig.numZ)): zStr = cfg.getZStr(z) currIP = IJ.openImage(imgFiles[z][t][0]) origImage = currIP.duplicate() if cfg.getValue(ELMConfig.debugOutput): WindowManager.setTempCurrentImage(currIP) IJ.saveAs( 'png', os.path.join( wellPath, "Orig_" + wellName + "_" + zStr + "_" + chanStr + ".png")) # We need to get to a grayscale image, which will be done differently for different channels dbgOutDesc = wellName + "_" + tStr + "_" + zStr + "_" + chanStr currIP = ELMImageUtils.getThresholdedMask(currIP, c, z, 1, chanName, cfg, wellPath, dbgOutDesc) if (not currIP): continue currProcessor = currIP.getProcessor() #WindowManager.setTempCurrentImage(currIP); #currIP.show() imgWidth = currIP.getWidth() imgHeight = currIP.getHeight() for x in range(0, imgWidth): for y in range(0, imgHeight): if not currProcessor.get(x, y) == 0x00000000: ptCount += 1 ptX = x * cfg.getValue(ELMConfig.pixelWidth) ptY = y * cfg.getValue(ELMConfig.pixelHeight) ptZ = -z * cfg.getValue(ELMConfig.pixelDepth) colorPix = origImage.getPixel(x, y) red = colorPix[0] green = colorPix[1] blue = colorPix[2] # Check that point meets color threshold aboveColorThresh = not cfg.hasValue(ELMConfig.pcloudColorThresh) \ or colorPix[chanPixBand] > cfg.getValue(ELMConfig.pcloudColorThresh) # Check that point isn't in exclusion zone outsideExclusion = not (cfg.hasValue(ELMConfig.pcloudExclusionX) and cfg.hasValue(ELMConfig.pcloudExclusionY)) \ or (x < cfg.getValue(ELMConfig.pcloudExclusionX) or y < cfg.getValue(ELMConfig.pcloudExclusionY)) if (aboveColorThresh and outsideExclusion): points.append([ptX, ptY, ptZ, red, green, blue]) elif (not aboveColorThresh): numColorThreshPts += 1 elif (not outsideExclusion): numExclusionPts += 1 currIP.close() origImage.close() print "\t\tTotal points considered: " + str(ptCount) print "\t\tColor Threshold Skipped " + str( numColorThreshPts) + " points." print "\t\tExclusion Zone Skipped " + str(numExclusionPts) + " points." numPoints = len(points) cloudName = chanName + "_" + tStr + "_cloud.ply" resultsFile = open(os.path.join(wellPath, cloudName), "w") resultsFile.write("ply\n") resultsFile.write("format ascii 1.0\n") resultsFile.write("element vertex " + str(numPoints) + "\n") resultsFile.write("property float x\n") resultsFile.write("property float y\n") resultsFile.write("property float z\n") resultsFile.write("property uchar red\n") resultsFile.write("property uchar green\n") resultsFile.write("property uchar blue\n") resultsFile.write("end_header\n") for line in points: resultsFile.write( "%f %f %f %d %d %d\n" % (line[0], line[1], line[2], line[3], line[4], line[5])) resultsFile.close() if numPoints > 0: compute3DStats(cfg, wellPath, wellName, chanName, cloudName, imgWidth, imgHeight) else: print( 'Well %s, channel %s (%s) - Skipping 3D stats since we have no points!' % (wellName, chanName, chanStr)) print ""
# Set the options. options = ['size=%s' % size] circularity_str = '%.3f-%.3f' % (circularity_min, circularity_max) options.append('circularity=%s' % circularity_str) if show.find('_') >= 0: show_str = '[%s]' % show.replace('_', ' ') else: show_str = show options.append('show=%s' % show_str) if display_results: options.append('display') if not all_results: options.append('summarize') if exclude_edges: options.append('exclude') if include_holes: options.append('include') # Always run "in_situ". options.append('in_situ') # Run the command. IJ.run(input_image_plus_copy, "Analyze Particles...", " ".join(options)) # Save outputs. if len(output_filename) > 0: # Save the ImagePlus object as a new image. IJ.saveAs(input_image_plus_copy, output_datatype, output_filename) if display_results and len(results_path) > 0: results_table = analyzer.getResultsTable() results_table.saveAs(results_path)
def saveResults(path): IJ.saveAs("Results", path)
def run(): """ Loads an image stack which contains both reference and target images for the registration Scales the images to have their largest side equal to longSide Registration is performed: - translation (brute force optimization) - rotation (brute force optimization) - sift registration - bunwarpj registration Calculation of the errors by different methods """ # load the input stack as an ImagePlus imp = IJ.openImage(filePath.getAbsolutePath()) stack = imp.getStack() sizeZ = imp.getStackSize() LAND_MARKS = 0 # Copy the reference and target slice refId = 1 ref = stack.getProcessor(refId).duplicate() if (Scale == 1): [ref, s] = scaleLongSide(ref, longSide) sizeZ = min(sizeZ, maxSlice) stackReg = ImageStack(ref.getWidth(), ref.getHeight()) stackReg.addSlice(ref) # = stack.duplicate() for i in range(2, sizeZ+1): targetId = i target = stack.getProcessor(targetId).duplicate() # Scale the slices: scale the reference slice using the longSide parameter, and use the same scale for the target slice. if (Scale == 1): target = scale(target, s) #ImagePlus('Ref',ref).show() #ImagePlus('Target',target).show() if (Reg == 1): if (translationReg == 1): target = translation(ref, target) if (rotationReg == 1): [rot, target] = rotationSingle(ref,target,rotationStep) if (siftReg == 1): [roiRef, roiTarget] = siftSingle(ref, target) impTarget = ImagePlus('Target',target) impTarget.setRoi(roiTarget) #impTarget.show() impRef = ImagePlus('Ref',ref) impRef.setRoi(roiRef) #impRef.show() LAND_MARKS = 1 if (bunwarpjReg == 1): target = bunwarpjSingle(impRef, impTarget, LAND_MARKS, 'direct_transfo_' + str(i) + '.txt', 'inverse_transfo_' + str(i) + '.txt') impTarget = ImagePlus('unwarpj_target', target) #impTarget.show() fileName = 'target_id' + str(targetId) + '.tif' IJ.saveAs(impTarget, "Tiff", os.path.join(saveDir.getAbsolutePath(), fileName)) #stackReg.setProcessor(target.convertToShortProcessor(), i) stackReg.addSlice(target) if (calculateError == 1): eCorrelation = zeros(sizeZ, 'f') eMSE = zeros(sizeZ, 'f') eMSE_ROI = zeros(sizeZ, 'f') eRMSE = zeros(sizeZ, 'f') eNRMSE = zeros(sizeZ, 'f') eCVRMSE = zeros(sizeZ, 'f') for i in range(1, sizeZ+1): ip = stackReg.getProcessor(i).duplicate() #ImagePlus('test',ip).show() eCorrelation[i-1], eMSE[i-1], eMSE_ROI[i-1], eRMSE[i-1], eNRMSE[i-1], eCVRMSE[i-1] = measureError(ref,ip) errorFileName = 'error.txt' errorFilePath = os.path.join(saveDir.getAbsolutePath(), errorFileName) writeCSV( errorFilePath, [eCorrelation,eMSE, eMSE_ROI, eRMSE,eNRMSE,eCVRMSE], ["Correlation","MSE","MSE_ROI","RMSE","N_RMSE","CV_RMSE"] )
def roiSave(path, roiname): IJ.saveAs("Selection", pjoin(path, roiname))
# Process a folder of AZtec.tif files and burn scale bars # expects a subfolder "tif" in a sample folder # # CCA licence # date who Comment # ---------- --- ----------------------------------------------------- # 2016-01-27 JRM From S: Drive from org.python.core import codecs codecs.setDefaultEncoding('utf-8') import os from ij import IJ, WindowManager import time theDir = "/Users/jrminter/Downloads/rutgers/" for i in range(42): st = "latex%04d" % (i+1) fi = "latex%02d" % (i+1) # print(fi) imp = WindowManager.getImage(st) if(imp != None): outPth = theDir + fi + ".png" IJ.saveAs(imp, "PNG", outPth) time.sleep(1) imp.close()
if template: txt_path = template(well, data_dir) IJ.run("Grid/Collection stitching", stitch_from_file_cmd(txt_path)) else: IJ.run( "Grid/Collection stitching", stitch_cmd(tiles, overlap, home_dir + data_dir, file_pattern, config)) if any(x > 1 for x in (channels, slices, frames)): print channels, slices, frames IJ.run( "Stack to Hyperstack...", "order=%s channels=%d slices=%d frames=%d display=Composite" % (order, channels, slices, frames)) ip = IJ.getImage() for i, (color, display_range) in enumerate(channel_luts): ip.setC(i + 1) ip.setDisplayRange(*display_range) IJ.run(color) ip.setCalibration(cal) IJ.saveAs("Tiff", savename(well, data_dir)) IJ.run("Close All") if use_template is True: template = make_template(well, data_dir) print 'completed without error'
# strImg = gitDir + relImg + "/bridge.gif" strImg = imgDir + relImg + "/out/bez-50X-1-ij-edf.tif" print(strImg) strFF = imgDir + relImg + "/ff/gain.tif" # 1. Open an image and it's flat field impExp = IJ.openImage(strImg) name = impExp.getShortTitle() impExp.show() impBkg = IJ.openImage(strFF) impSc = jmg.flatFieldCorrectRGB(impExp, impBkg) impSc.show() name = name + "-sc" impSc.setTitle(name) strImg = imgDir + relImg + "/out/" + name + ".tif" IJ.saveAs("Tiff", strImg)
def run(): """ Loads an image stack which contains both reference and target images for the registration Scales the images to have their largest side equal to longSide Registration is performed: - translation (brute force optimization) - rotation (brute force optimization) - sift registration - bunwarpj registration Calculation of the errors by different methods """ # load the input stack as an ImagePlus imp = IJ.openImage(filePath.getAbsolutePath()) stack = imp.getStack() sizeZ = imp.getStackSize() LAND_MARKS = 0 # Copy the reference and target slice refId = 1 ref = stack.getProcessor(refId).duplicate() if (Scale == 1): [ref, s] = scaleLongSide(ref, longSide) sizeZ = min(sizeZ, maxSlice) stackReg = ImageStack(ref.getWidth(), ref.getHeight()) stackReg.addSlice(ref) # = stack.duplicate() for i in range(2, sizeZ + 1): targetId = i target = stack.getProcessor(targetId).duplicate() # Scale the slices: scale the reference slice using the longSide parameter, and use the same scale for the target slice. if (Scale == 1): target = scale(target, s) #ImagePlus('Ref',ref).show() #ImagePlus('Target',target).show() if (Reg == 1): if (translationReg == 1): target = translation(ref, target) if (rotationReg == 1): [rot, target] = rotationSingle(ref, target, rotationStep) if (siftReg == 1): [roiRef, roiTarget] = siftSingle(ref, target) impTarget = ImagePlus('Target', target) impTarget.setRoi(roiTarget) #impTarget.show() impRef = ImagePlus('Ref', ref) impRef.setRoi(roiRef) #impRef.show() LAND_MARKS = 1 if (bunwarpjReg == 1): target = bunwarpjSingle(impRef, impTarget, LAND_MARKS, 'direct_transfo_' + str(i) + '.txt', 'inverse_transfo_' + str(i) + '.txt') impTarget = ImagePlus('unwarpj_target', target) #impTarget.show() fileName = 'target_id' + str(targetId) + '.tif' IJ.saveAs(impTarget, "Tiff", os.path.join(saveDir.getAbsolutePath(), fileName)) #stackReg.setProcessor(target.convertToShortProcessor(), i) stackReg.addSlice(target) if (calculateError == 1): eCorrelation = zeros(sizeZ, 'f') eMSE = zeros(sizeZ, 'f') eMSE_ROI = zeros(sizeZ, 'f') eRMSE = zeros(sizeZ, 'f') eNRMSE = zeros(sizeZ, 'f') eCVRMSE = zeros(sizeZ, 'f') si = zeros(sizeZ, 'f') si1 = zeros(sizeZ, 'f') si2 = zeros(sizeZ, 'f') eCVRMSE = zeros(sizeZ, 'f') for i in range(1, sizeZ + 1): ip = stackReg.getProcessor(i).duplicate() #ip = stack.getProcessor(i).duplicate() #ImagePlus('test',ip).show() eCorrelation[i - 1], eMSE[i - 1], eMSE_ROI[i - 1], eRMSE[ i - 1], eNRMSE[i - 1], eCVRMSE[i - 1] = measureError(ref, ip) si[i - 1], si1[i - 1], si2[i - 1] = VOP(ref, ip) errorFileName = 'error.txt' errorFilePath = os.path.join(saveDir.getAbsolutePath(), errorFileName) writeCSV(errorFilePath, [ si, si1, si2, eCorrelation, eMSE, eMSE_ROI, eRMSE, eNRMSE, eCVRMSE ], [ "si", "si1", "si2", "Correlation", "MSE", "MSE_ROI", "RMSE", "N_RMSE", "CV_RMSE" ])
IJ.run(image_plus_copy, "Despeckle", "") elif noise == 'remove_outliers': IJ.run(image_plus_copy, "Remove Outliers", "radius=&radius threshold=&threshold which=&which_outliers") elif noise == 'remove_nans': IJ.run(image_plus_copy, "Remove NaNs", "") elif noise == 'rof_denoise': IJ.run(image_plus_copy, "ROF Denoise", "") elif noise == 'randomj': if randomj == 'randomj_binomial': IJ.run(image_plus_copy, "RandomJ Binomial", "trials=&trials probability=&probability insertion=&insertion") elif randomj == 'randomj_exponential': IJ.run(image_plus_copy, "RandomJ Exponential", "lambda=&lammbda insertion=&insertion") elif randomj == 'randomj_gamma': IJ.run(image_plus_copy, "RandomJ Gamma", "order=&order insertion=&insertion") elif randomj == 'randomj_gaussian': IJ.run(image_plus_copy, "RandomJ Gaussian", "mean=&mean sigma=&sigma insertion=&insertion") elif randomj == 'randomj_poisson': IJ.run(image_plus_copy, "RandomJ Poisson", "mean=&mean insertion=&insertion") elif randomj == 'randomj_uniform': IJ.run(image_plus_copy, "RandomJ Uniform", "min=&min max=&max insertion=&insertion") # Save the ImagePlus object as a new image. IJ.saveAs(image_plus_copy, image_datatype, tmp_output_path)
import os # start clean IJ.run("Close All") tif_path = img_dir + "/nalco-img-04cr.tif" imp = IJ.openImage(tif_path) str_info = """Analyst: J. R. Minter Date Recorded: 2004-08-10 14:05 Sample: Nalco silica Instrument: Philips CM20 Conditions: CryoTEM 200 kV 38,000X LowDose Notes: Original image size 1024x1024x16 bits/px Comment: 2019-06-19: Rotated and cropped in Fiji to get best particles. """ imp.setProperty("Info", str_info) imp.show() IJ.saveAs("TIF", tif_path) imp.close() imp2 = IJ.openImage(tif_path) info_str = imp2.getInfoProperty() imp2.show() print(info_str)