def RunShapeFileImportTool(): """ <Script> <Author>admin</Author> <Description>Please enter script description here</Description> </Script> """ # Get all the files in the directory directory = r"C:\temp\Del_Shape" #directory with shape files FileList = Directory.GetFiles(directory) DB_folder = '/xx' #folder to import shape files to for file in FileList: fullPath = Path.Combine(directory, file) if Path.GetExtension(fullPath) == '.shp': featureClassName = '/' + Path.GetFileNameWithoutExtension( fullPath) #filenameWithoutExtension inputItems = gisMgr.FeatureClassGroupList.Get(DB_folder) if inputItems == None: inputItems = gisMgr.FeatureClassGroupList.CreateNew(DB_folder) coordinateSystem = gisMgr.DefaultCoordinateSystem ShapeFileImportTool(inputItems, coordinateSystem, featureClassName, fullPath)
def GetCurrentSessionIds(folderPath): ids = [] file_list = glob.glob(folderPath + '\\*' + '.txt') for f in file_list: ids.append( AdjustSessionIdFileNameBack(Path.GetFileNameWithoutExtension(f))) return ids
def run_postprocessing(image, parameters={}, func='topography'): """Example template to add post-processing functions. :param image: Image to be processed :type image: ZenImage :param parameters: Dictionary with processing parameters for function, defaults to {} :type parameters: dict, optional :param func: Function name, defaults to 'topography' :type func: str, optional :return: image or processed image :rtype: ZenImage """ if func == 'topography': noise_low = parameters['noise_low'] noise_high = parameters['noise_high'] outputfolder = parameters['outputfolder'] ext = parameters['extension'] # converting to topo, with defined FZ noisecut # in filter settings: 0-255 means no filter, 1-254 means cut one gray scale from top and from bottom imgtop = Zen.Processing.Transformation.Topography.CreateTopography( image, noise_low, noise_high) # saving file to the directory topo_filepath = Path.Combine( outputfolder, Path.GetFileNameWithoutExtension(image.FileName) + ext) Zen.Processing.Utilities.ExportHeightmapFromTopography( imgtop, topo_filepath) print('Exported to : ', topo_filepath) imgtop.Close() return image
def ExecuteFile(self, filename, globalVar=None): moduleEO = self.CreateScope() self.dbgmodule = moduleEO self.ExecuteFileInScope(filename, moduleEO) globalVar = globalVar or Path.GetFileNameWithoutExtension(filename) runtime.DynamicObjectHelpers.SetMember(self.Globals, globalVar, moduleEO) return moduleEO
def SaveCoverAsImage(books): for book in books: bookFileInfo = FileInfo(book.FilePath) bookNameWithoutExt = Path.GetFileNameWithoutExtension(book.FilePath); dirName = bookFileInfo.DirectoryName destinationFilePath = dirName + "\\" + bookNameWithoutExt + '.jpg' pageImage = ComicRack.App.GetComicPage(book, book.FrontCoverPageIndex) pageImage.Save(destinationFilePath, ImageFormat.Jpeg)
def run(self, Mml2vgmInfo, index): #設定値の読み込み Mml2vgmInfo.loadSetting() #初回のみ(設定値が無いときのみ)git.exeの場所をユーザーに問い合わせ、設定値として保存する gt = Mml2vgmInfo.getSettingValue("soxpath") if gt is None: gt = Mml2vgmInfo.fileSelect( "sox.exeを選択してください(この選択内容は設定値として保存され次回からの問い合わせはありません)") if not Mml2vgmInfo.confirm("sox.exeの場所は以下でよろしいですか\r\n" + gt): return None Mml2vgmInfo.setSettingValue("soxpath", gt) Mml2vgmInfo.saveSetting() #念のため if gt is None or gt == "": Mml2vgmInfo.msg("sox.exeを指定してください") return None #ファイル情報の整理 for fnf in Mml2vgmInfo.fileNamesFull: ext = Path.GetExtension(fnf) bas = Path.GetFileNameWithoutExtension(fnf) wp = Path.GetDirectoryName(fnf) Directory.SetCurrentDirectory(wp) si = ScriptInfo() # 引数を組み立てる if index == 0: args = "--i \"" + bas + ext + "\"" elif index == 1: # -b 8bit # -c 1 mono # -r 14k rate 14KHz args = bas + ext + " -b 8 -r 8k -c 1 " + bas + "_8k" + ext elif index == 2: args = bas + ext + " -r 14k -e signed-integer -c 1 " + bas + "_14k" + ext elif index == 3: args = bas + ext + " -r 16k -e signed-integer -c 1 " + bas + "_16k" + ext elif index == 4: args = bas + ext + " -r 18500 -e signed-integer -c 1 " + bas + "_18500" + ext ret = Mml2vgmInfo.runCommand(gt, args, True) if ret != "": Mml2vgmInfo.msg(ret) else: if index != 0: Mml2vgmInfo.msg("success") Mml2vgmInfo.refreshFolderTreeView() return si
def run(self, Mml2vgmInfo, index): #設定値の読み込み Mml2vgmInfo.loadSetting() #初回のみ(設定値が無いときのみ)mucom88.exeの場所をユーザーに問い合わせ、設定値として保存する mc = Mml2vgmInfo.getSettingValue("mucom88path") if mc is None: mc = Mml2vgmInfo.fileSelect( "mucom88.exeを選択してください(この選択内容は設定値として保存され次回からの問い合わせはありません)") if not Mml2vgmInfo.confirm("mucom88.exeの場所は以下でよろしいですか\r\n" + mc): return None Mml2vgmInfo.setSettingValue("mucom88path", mc) Mml2vgmInfo.saveSetting() #念のため if mc is None or mc == "": Mml2vgmInfo.msg("mucom88.exeを指定してください") return None #ファイル選択 muc = Mml2vgmInfo.fileSelect("mucファイルの選択") if muc is None: return None #ファイル情報の整理 #Mml2vgmInfo.msgLogWindow(muc) wp = Path.GetDirectoryName(muc) #Mml2vgmInfo.msgLogWindow(wp) Directory.SetCurrentDirectory(wp) #mucom88.exeでコンパイルを行いmubファイルを生成する args = "-c " + muc Mml2vgmInfo.runCommand(mc, args, True) #mubファイルが出来たかチェック(mucom88.exeはコンパイルが成功するとmucom88.mubというファイルができる) mm = Path.Combine(wp, "mucom88.mub") #Mml2vgmInfo.msgLogWindow(mm) if not File.Exists(mm): return None #mucom88.mubを本来のファイル名にリネーム mub = Path.Combine(wp, Path.GetFileNameWithoutExtension(muc) + ".mub") #Mml2vgmInfo.msgLogWindow(mub) File.Delete(mub) File.Move(mm, mub) #mucom88.exeで演奏を開始 Mml2vgmInfo.runCommand(mc, mub, False) #戻り値を生成(何もしないけど念のため) si = ScriptInfo() si.responseMessage = "" return si
def run(self, Mml2vgmInfo, index): #設定値の読み込み Mml2vgmInfo.loadSetting() #初回のみ(設定値が無いときのみ)sox.exeの場所をユーザーに問い合わせ、設定値として保存する gt = Mml2vgmInfo.getSettingValue("soxpath") if gt is None: gt = Mml2vgmInfo.fileSelect( "sox.exeを選択してください(この選択内容は設定値として保存され次回からの問い合わせはありません)") if not Mml2vgmInfo.confirm("sox.exeの場所は以下でよろしいですか\r\n" + gt): return None Mml2vgmInfo.setSettingValue("soxpath", gt) Mml2vgmInfo.saveSetting() #念のため if gt is None or gt == "": Mml2vgmInfo.msg("sox.exeを指定してください") return None #ファイル情報の整理 for fnf in Mml2vgmInfo.fileNamesFull: ext = Path.GetExtension(fnf) bas = Path.GetFileNameWithoutExtension(fnf) wp = Path.GetDirectoryName(fnf) Directory.SetCurrentDirectory(wp) si = ScriptInfo() argList = [ "--i \"{0}{1}\"", "\"{0}{1}\" -r 8000 -b 8 -c 1 \"{0}_8k{1}\"", "\"{0}{1}\" -r 14000 -b 8 -c 1 \"{0}_14k{1}\"", "\"{0}{1}\" -r 16000 -b 8 -c 1 \"{0}_16k{1}\"", "\"{0}{1}\" -r 18500 -b 8 -c 1 \"{0}_18500{1}\"", "\"{0}{1}\" -b 16 -r 14000 -e signed-integer -c 1 \"{0}_16b_14k{1}\"", "\"{0}{1}\" -b 16 -r 16000 -e signed-integer -c 1 \"{0}_16b_16k{1}\"", "\"{0}{1}\" -b 16 -r 18500 -e signed-integer -c 1 \"{0}_16b_18500{1}\"", "\"{0}{1}\" -n trim 0 1.5 noiseprof \"{0}.noise-profile\"", "\"{0}{1}\" \"{0}_cleaned{1}\" noisered \"{0}.noise-profile\" 0.2 " ] args = argList[index].format(bas, ext) ret = Mml2vgmInfo.runCommand(gt, args, True) if ret != "": Mml2vgmInfo.msg(ret) else: if index != 0: Mml2vgmInfo.msg("success") Mml2vgmInfo.refreshFolderTreeView() return si
def DumpPlainTextLogFile(): plainTextLogFilePath = None logFilePath = GetLogFilePath() if not str.IsNullOrWhiteSpace(logFilePath): plainTextLogFilePath = Path.Combine( Path.GetDirectoryName(logFilePath), Path.GetFileNameWithoutExtension(logFilePath) + ".txt") try: File.WriteAllLines(plainTextLogFilePath, LogFile.ReadLinesAsPlainText(logFilePath)) except Exception, e: plainTextLogFilePath = None
def FileComboBox_SelectionChanged(self, sender, e): self.clear_plot() if self.FileComboBox.SelectedIndex != -1: comboIndex = self.FileComboBox.SelectedIndex file_name = self.file_names[comboIndex] data = parse_file(file_name) stem = Path.GetFileNameWithoutExtension(file_name) fig = self.generate_plot( x=data['Stage_StageReadings_StagePasteMins1'], y=data['Stage_StageReadings_StagePasteDive1'], title=stem, ) self.set_plot(fig)
def convert_files(doc_path): directory = DirectoryInfo(doc_path) files = directory.GetFiles("*.doc") for file_info in files: text = doc_to_text(Path.Combine(doc_path, file_info.Name)) stream_writer = File.CreateText( Path.GetFileNameWithoutExtension(file_info.Name) + ".txt") stream_writer.Write(text) stream_writer.Close() return
def main(): if len(sys.argv) != 2: print "Usage: ipy run_compiled.py <testfile.py>" sys.exit(-1) testName = sys.argv[1] print "Compiling ", testName ,"..." clr.CompileModules("compiledTest.dll", testName) File.Move(testName, testName+".bak") try: print "Running test from compiled binary..." clr.AddReference("compiledTest") __import__(Path.GetFileNameWithoutExtension(testName)) finally: File.Move(testName+".bak" , testName)
def OptimizeAllIFCFilesinFolder(directoryPath): returnvalue = res.Result() # check if ifc optimizer is installed: if(cp.FileExist(solibriInstallPath_)): returnvalue.message = 'Solibri IFC optimizer is installed.' ifcFiles = cp.GetFiles(directoryPath, '.ifc') filesToDelete = [] filesToRename = [] if(len(ifcFiles) > 0): returnvalue.AppendMessage('found ifc files: ' + str(len(ifcFiles))) for ifcFile in ifcFiles: s = subprocess.check_call([r'C:\Program Files\Solibri\IFCOptimizer\Solibri IFC Optimizer.exe', '-in=' + ifcFile, '-out=' + directoryPath, '-ifc', '-force']) # check what came back if (s == 0): #all went ok: returnvalue.AppendMessage('Optimized file: '+str(ifcFile)) filesToDelete.append(ifcFile) # full file path # get the rename information # contains old and new file name rename = [] p = cp.GetFolderPathFromFile(ifcFile) if(p != ''): newFilePath = str(p)+'\\'+ str(Path.GetFileNameWithoutExtension(ifcFile))+'_optimized.ifc' rename.append(newFilePath) rename.append(ifcFile) filesToRename.append(rename) else: # something went wrong returnvalue.UpdateSep(False, 'Failed to optimize file: '+ str(ifcFile)) # clean up for fileToDelete in filesToDelete: statusDelete = cp.FileDelete(fileToDelete) if(statusDelete): returnvalue.AppendMessage('Deleted original file: ' + str(fileToDelete)) else: returnvalue.UpdateSep(False,'Failed to delete original file: '+ str(fileToDelete)) for fileToRename in filesToRename: statusRename = cp.RenameFile(fileToRename[0], fileToRename[1]) if(statusRename): returnvalue.AppendMessage('Renamed original file: ' + str(fileToRename[0]) + ' to: ' + str(fileToRename[1])) else: returnvalue.UpdateSep(False,'Failed to rename original file: '+ str(fileToRename[0])) else: returnvalue.AppendMessage('No IFC files found in directory: '+ str(directoryPath)) else: returnvalue.UpdateSep(False, 'No IFC optimizer installed at: '+ str(solibriInstallPath_)) return returnvalue
def run_postprocessing(image, parameters={}, func='topography'): if func == 'topography': noise_low = parameters['noise_low'] noise_high = parameters['noise_high'] outputfolder = parameters['outputfolder'] ext = parameters['extension'] # converting to topo, with defined FZ noisecut # in filter settings: 0-255 means no filter, 1-254 means cut one gray scale from top and from bottom imgtop = Zen.Processing.Transformation.Topography.CreateTopography(image, noise_low, noise_high) # saving file to the directory topo_filepath = Path.Combine(outputfolder, Path.GetFileNameWithoutExtension(image.FileName) + ext) Zen.Processing.Utilities.ExportHeightmapFromTopography(imgtop, topo_filepath) print('Exported to : ', topo_filepath) imgtop.Close() return image
def OpenFileButton_Click(self, sender, e): dlg = OpenFileDialog() dlg.DefaultExt = ".txt" dlg.Filter = "Text Files (*.txt)|*.txt" dlg.Multiselect = True if dlg.ShowDialog() == True: self.file_names = dlg.FileNames self.combo_clear() self.log_clear() self.log_append( f'Successfully loaded {len(self.file_names)} stages:') for file_name in self.file_names: stem = Path.GetFileNameWithoutExtension(file_name) self.log_append(stem) self.FileComboBox.Items.Add(stem) self.SaveXMLButton.IsEnabled = True self.FileComboBox.IsEnabled = True
# load image in Zen img = Zen.Application.LoadImage(czifile, False) Zen.Application.Documents.Add(img) metadata = jt.fill_metadata(img) IMAGEJ = 'c:\\Fiji\\ImageJ-win64.exe' IMAGEJDIR = Path.GetDirectoryName(IMAGEJ) SCRIPT = 'c:\\Fiji\\scripts\\3d_analytics_fromZEN.py' # define script parameters params = {} params['IMAGEJ'] = IMAGEJ params['IMAGEJSCRIPT'] = SCRIPT params['IMAGE'] = czifile params['IMAGEDIR'] = Path.GetDirectoryName(czifile) params['FILEWOEXT'] = Path.GetFileNameWithoutExtension(czifile) params['HEADLESS'] = True # define processing parameters params['JSONPARAMSFILE'] = Path.Combine(params['IMAGEDIR'], params['FILEWOEXT'] + '.json') params['LABEL_CONNECT'] = 6 params['LABEL_COLORIZE'] = False params['MINVOXSIZE'] = 1000 # define outputs params['SAVEFORMAT'] = 'ome.tiff' params['RESULTTABLE'] = '' params['RESULTIMAGE'] = '' # update dictionary
def GetRevitModelName(revitFilePath): return Path.GetFileNameWithoutExtension(revitFilePath)
def onSignInClick(source, rea): config = None directory = Path.Combine( Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData), Assembly.GetEntryAssembly().GetName().Name) backgroundBrush = None textColor = SystemColors.ControlTextBrush if Directory.Exists(directory): fileName1 = Path.GetFileName(Assembly.GetEntryAssembly().Location) for fileName2 in Directory.EnumerateFiles(directory, "*.config"): if fileName1.Equals( Path.GetFileNameWithoutExtension(fileName2)): exeConfigurationFileMap = ExeConfigurationFileMap() exeConfigurationFileMap.ExeConfigFilename = fileName2 config = ConfigurationManager.OpenMappedExeConfiguration( exeConfigurationFileMap, ConfigurationUserLevel.None) if config is None: config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None) directory = None if config.AppSettings.Settings["BackgroundImage"] is not None: fileName = config.AppSettings.Settings[ "BackgroundImage"].Value if directory is None else Path.Combine( directory, config.AppSettings.Settings["BackgroundImage"].Value) fs = None bi = BitmapImage() try: fs = FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read) bi.BeginInit() bi.StreamSource = fs bi.CacheOption = BitmapCacheOption.OnLoad bi.CreateOptions = BitmapCreateOptions.None bi.EndInit() finally: if fs is not None: fs.Close() backgroundBrush = ImageBrush(bi) backgroundBrush.TileMode = TileMode.Tile backgroundBrush.ViewportUnits = BrushMappingMode.Absolute backgroundBrush.Viewport = Rect(0, 0, bi.Width, bi.Height) backgroundBrush.Stretch = Stretch.None if backgroundBrush.CanFreeze: backgroundBrush.Freeze() if backgroundBrush is None and config.AppSettings.Settings[ "BackgroundColor"] is not None: if config.AppSettings.Settings["BackgroundColor"].Value.Length > 0: backgroundBrush = SolidColorBrush( ColorConverter.ConvertFromString( config.AppSettings.Settings["BackgroundColor"].Value)) if backgroundBrush.CanFreeze: backgroundBrush.Freeze() if config.AppSettings.Settings["TextColor"] is not None: if config.AppSettings.Settings["TextColor"].Value.Length > 0: textColor = ColorConverter.ConvertFromString( config.AppSettings.Settings["TextColor"].Value) textBrush = SolidColorBrush(textColor) if textBrush.CanFreeze: textBrush.Freeze() window = Window() def onClick(source, args): global username, password if not String.IsNullOrEmpty( usernameTextBox.Text) and not String.IsNullOrEmpty( passwordBox.Password): username = usernameTextBox.Text password = passwordBox.Password def onSave(): try: fs = None sr = None sw = None try: fs = FileStream(__file__, FileMode.Open, FileAccess.ReadWrite, FileShare.Read) encoding = UTF8Encoding(False) sr = StreamReader(fs, encoding, True) lines = Regex.Replace( Regex.Replace( sr.ReadToEnd(), "username\\s*=\\s*\"\"", String.Format("username = \"{0}\"", username), RegexOptions.CultureInvariant), "password\\s*=\\s*\"\"", String.Format("password = \"{0}\"", password), RegexOptions.CultureInvariant) fs.SetLength(0) sw = StreamWriter(fs, encoding) sw.Write(lines) finally: if sw is not None: sw.Close() if sr is not None: sr.Close() if fs is not None: fs.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace) def onCompleted(task): global menuItem for window in Application.Current.Windows: if window is Application.Current.MainWindow and window.ContextMenu is not None: if window.ContextMenu.Items.Contains(menuItem): window.ContextMenu.Items.Remove(menuItem) window.ContextMenu.Opened -= onOpened if window.ContextMenu.Items[10].GetType( ).IsInstanceOfType(window.ContextMenu.Items[ window.ContextMenu.Items.Count - 4]): window.ContextMenu.Items.RemoveAt(10) menuItem = None Task.Factory.StartNew( onSave, TaskCreationOptions.LongRunning).ContinueWith( onCompleted, TaskScheduler.FromCurrentSynchronizationContext()) window.Close()
if surface_result: surface = 'True' elif not surface_result: surface = 'False' # define the actual CZI file to be analyzed czifile = CZIdict[cziname] czifile_cmd = '"' + CZIdict[cziname] + '"' params = czifile_cmd + ' ' + writecsv + ' ' + separator + ' ' + save + ' ' + saveformat_result + ' ' + surface print 'CZI file to be used: ', czifile print 'Parameter : ', params # when option to save the figure was set if save_result: savename = Path.GetFileNameWithoutExtension( czifile) + '_planetable_XYZ-Pos.' + saveformat_result savename_full = Path.Combine(Path.GetDirectoryName(czifile), savename) print 'Savename: ', savename_full # delete older version of the figure if existing if File.Exists(savename_full): File.Delete(savename_full) print 'Deleted older figure: ', savename_full # start the data display script as an external application app = Process() app.StartInfo.FileName = SCRIPT app.StartInfo.Arguments = params app.Start() # waits until the python figure was closed app.WaitForExit()
# specify image image_to_analyze = r'c:\Data\Nanoparticles.tif' # define the image analysis setting iasfilename = r'c:\Users\XYZ\Documents\Carl Zeiss\ZEN\Documents\Image Analysis Settings\Nanoparticle Segmentation ZEN25.czias' # define the external plot script or tool pythonexe = r'C:\Anaconda3\python.exe' script = r'c:\Data\External_Python_Scripts_for_OAD\RMI_plot_nanoparticles.py' # load imnage image = Zen.Application.LoadImage(image_to_analyze) Zen.Application.Documents.Add(image) outputpath = Path.GetDirectoryName(image_to_analyze) resultname = Path.GetFileNameWithoutExtension(image.Name) # loead CZIAS image analysis setting ias = ZenImageAnalysisSetting() ias.Load(iasfilename) classnames = ias.GetRegionClassNames() if analyze_inplace: Zen.Analyzing.Analyze(image, ias) # run the image analyis pipeline and directly create a table all_tables = Zen.Analyzing.AnalyzeToTable(image, ias) for class_table in all_tables: if show_tables:
print 'Confidence Threshold Value : ', conf_th print 'Add Segmented Image to Original : ', addseg2orig print 'Adapt PixelType of Segmented Image : ', adaptpx print '-----------------------------------------------------------------------------' print 'Segmenting ...' # extract select channel from active image substr = 'C(' + str(chdict[channelname]) + ')' image = Zen.Processing.Utilities.CreateSubset(activeimage, substr, False) # do the pixel classification for the current image seg = classify(image, modelname, use_confidence=use_conf, confidence_threshold=conf_th, format=segmentationformat, extractclass=extract, addseg=False, classid=extract_id + 1, adapt_pixeltype=adaptpx) if addseg2orig: # add segmentation result to the original image orig_seg = Zen.Processing.Utilities.AddChannels(activeimage, seg) Zen.Application.Documents.Add(orig_seg) seg_name = Path.GetFileNameWithoutExtension( activeimagefilename) + '_seg' + Path.GetExtension(activeimagefilename) orig_seg.Name = seg_name print 'Done.'
if verbose: for i in info: print i.Key, ':\t ', i.Value # get additional metainformation metadata = getMetaDataExtra(activeimage, usecounter, fullwellinfo=fwinfo) if verbose: for k, v in metadata.iteritems(): print k, ':\t', v # concatenate the two python dictionaries metadata.update(info) # Create new table with 2 col with name Key and Value table1 = ZenTable('MetaData - ' + Path.GetFileNameWithoutExtension(cziname)) table1.Columns.Add('Name',str) table1.Columns.Add('Value',str) # fill the table from the dictionary r = 0 for k, v in metadata.iteritems(): table1.Rows.Add() table1.SetValue(r, 0, k) table1.SetValue(r, 1, v) r = r + 1 # sort the table table1_sorted = SortZenTable(table1, 'Name') Zen.Application.Documents.Add(table1_sorted)
if not File.Exists(script): message = 'Plot Script not found.' print(message) raise SystemExit if File.Exists(script): message = 'Plot Script found.' print(message) # load image and add it to ZEN and get the image path image_to_analyze = r'c:\Testdata\Translocation_comb_96_5ms.czi' image = Zen.Application.LoadImage(image_to_analyze) Zen.Application.Documents.Add(image) outputpath = Path.GetDirectoryName(image_to_analyze) resultname = Path.GetFileNameWithoutExtension(image.Name) # define the image analysis setting and run the image analysis on the active image iasfilename = r'c:\Image Analysis Settings\Translocation_ZEN2.6.czias' ias = ZenImageAnalysisSetting() ias.Load(iasfilename) Zen.Analyzing.Analyze(image, ias) """ # Create data list with results for all regions (e.g. all nuclei) table_all = Zen.Analyzing.CreateRegionsTable(image) Zen.Application.Documents.Add(table_all) # Create data list with results for each region (e.g. every single nucleus) table_single = Zen.Analyzing.CreateRegionTable(image) Zen.Application.Documents.Add(table_single) """
from System.Diagnostics import Process from System.IO import File, Path, Directory # clear output Zen.Application.Documents.RemoveAll(False) Zen.Application.MacroEditor.ClearMessages() # define output folder outputpath = r'c:\Output' # initialize Zen experiment and run it experiment_filename = r'ML_96_Wellplate_Castor.czexp' exp = ZenExperiment() exp.Load(experiment_filename) image2analyze = Zen.Acquisition.Execute(exp) # save the image savename = Path.GetFileNameWithoutExtension(experiment_filename) + '.czi' image2analyze.Save(Path.Combine(outputpath, savename)) # define the image analysis setting and run the image analysis on the active image iafilename = r'c:\Users\M1SRH\Documents\Carl Zeiss\ZEN\Documents\Image Analysis Settings\Count_Cells_DAPI_96well.czias' ias = ZenImageAnalysisSetting() ias.Load(iafilename) Zen.Analyzing.Analyze(image2analyze, ias) # Create data list with results for all regions (e.g. all nuclei) table_all = Zen.Analyzing.CreateRegionsTable(image2analyze) Zen.Application.Documents.Add(table_all) # Create data list with results for each region (e.g. every single nucleus) table_single = Zen.Analyzing.CreateRegionTable(image2analyze) Zen.Application.Documents.Add(table_single)
def renderArgument(self): renderEngines = { "V-Ray": "0", "V-Ray RT": "1", u"V-Ray RT(OpenCL)": "3", u"V-Ray RT(CUDA)": "5" } sRGBOptions = ["On", "Off"] displayWindow = self.GetBooleanPluginInfoEntryWithDefault( "DisplayVFB", False) autoclose = self.GetBooleanPluginInfoEntryWithDefault( "AutocloseVFB", True) displaySRGB = self.GetPluginInfoEntryWithDefault("DisplaySRGB", "On") # Get the frame information. startFrame = self.GetStartFrame() endFrame = self.GetEndFrame() singleRegionJob = self.IsTileJob() singleRegionFrame = str(self.GetStartFrame()) singleRegionIndex = self.GetCurrentTaskId() separateFilesPerFrame = self.GetBooleanPluginInfoEntryWithDefault( "SeparateFilesPerFrame", False) regionRendering = self.GetBooleanPluginInfoEntryWithDefault( "RegionRendering", False) rtEngine = self.GetPluginInfoEntryWithDefault("VRayEngine", "V-Ray") rtTimeout = self.GetFloatPluginInfoEntryWithDefault("RTTimeout", 0.00) rtNoise = self.GetFloatPluginInfoEntryWithDefault("RTNoise", 0.001) rtSampleLevel = self.GetIntegerPluginInfoEntryWithDefault( "RTSamples", 0) # Can't allow it to be interactive or display the image because that would hang the slave renderarguments = " -scenefile=\"" + self.tempSceneFilename + "\" -interactive=0" if not displayWindow: renderarguments += " -display=0" # Default value is 1 else: if autoclose: renderarguments += " -autoclose=1" # Default value is 0 renderarguments += " -displaySRGB=%s" % ( sRGBOptions.index(displaySRGB) + 1) renderarguments += " -rtEngine=%s" % renderEngines[rtEngine.strip()] if not rtEngine == "V-Ray": renderarguments += " -rtTimeOut=%s -rtNoise=%s -rtSampleLevel=%s" % ( rtTimeout, rtNoise, rtSampleLevel) renderarguments += " -frames=" + str(startFrame) if endFrame > startFrame: renderarguments += "-" + str(endFrame) # Set the output path. outputFile = self.GetPluginInfoEntryWithDefault("OutputFilename", "").strip() if outputFile != "": outputFile = RepositoryUtils.CheckPathMapping(outputFile) outputFile = PathUtils.ToPlatformIndependentPath(outputFile) if regionRendering: outputPath = Path.GetDirectoryName(outputFile) outputFileName = Path.GetFileNameWithoutExtension(outputFile) outputExtension = Path.GetExtension(outputFile) if singleRegionJob: outputFile = os.path.join( outputPath, ("_tile%s_" % singleRegionIndex) + outputFileName + outputExtension) else: currTile = self.GetIntegerPluginInfoEntryWithDefault( "CurrentTile", 1) outputFile = os.path.join(outputPath, ("_tile%d_" % currTile) + outputFileName + outputExtension) renderarguments += " -imgFile=\"" + outputFile + "\"" # Now set the rest of the options. renderarguments += " -numThreads=" + str(self.GetThreadCount()) width = self.GetIntegerPluginInfoEntryWithDefault("Width", 0) if width > 0: renderarguments += " -imgWidth=" + str(width) height = self.GetIntegerPluginInfoEntryWithDefault("Height", 0) if height > 0: renderarguments += " -imgHeight=" + str(height) if regionRendering: regionNumString = "" if singleRegionJob: regionNumString = str(singleRegionIndex) #Coordinates In Pixels will always be true when using the common tilerendering code. if self.GetBooleanPluginInfoEntryWithDefault( "CoordinatesInPixels", False): #With the coordinates already being in pixels we do not need to modify the coordinates. xStart = self.GetIntegerPluginInfoEntryWithDefault( "RegionXStart" + regionNumString, 0) xEnd = self.GetIntegerPluginInfoEntryWithDefault( "RegionXEnd" + regionNumString, 0) yStart = self.GetIntegerPluginInfoEntryWithDefault( "RegionYStart" + regionNumString, 0) yEnd = self.GetIntegerPluginInfoEntryWithDefault( "RegionYEnd" + regionNumString, 0) else: self.LogWarning( "Using deprecated coordinate system. Please submit new jobs to use the new coordinates system." ) xStart = round( self.GetFloatPluginInfoEntryWithDefault( "RegionXStart" + regionNumString, 0) * width) xEnd = round( self.GetFloatPluginInfoEntryWithDefault( "RegionXEnd" + regionNumString, 0) * width) yStart = round( self.GetFloatPluginInfoEntryWithDefault( "RegionYStart" + regionNumString, 0) * height) yEnd = round( self.GetFloatPluginInfoEntryWithDefault( "RegionYEnd" + regionNumString, 0) * height) renderarguments += " -region=%d;%d;%d;%d" % (xStart, yStart, xEnd, yEnd) disableProgressColor = self.GetBooleanConfigEntryWithDefault( "DisableProgressColor", False) if disableProgressColor: renderarguments += " -DisableProgressColor=0" renderarguments += " " + self.GetPluginInfoEntryWithDefault( "CommandLineOptions", "") yetiSearchPaths = [] searchPathIndex = 0 while True: searchPath = self.GetPluginInfoEntryWithDefault( "YetiSearchPath" + str(searchPathIndex), "").replace("\\", "/") if not searchPath: break yetiSearchPaths.append( RepositoryUtils.CheckPathMapping(searchPath)) searchPathIndex += 1 if len(yetiSearchPaths) > 0: oldSearchPath = os.environ.get("PG_IMAGE_PATH") if oldSearchPath: yetiSearchPaths.append(oldSearchPath) yetiSepChar = ":" if SystemUtils.IsRunningOnWindows(): yetiSepChar = ";" self.SetProcessEnvironmentVariable( "PG_IMAGE_PATH", yetiSepChar.join(yetiSearchPaths)) return renderarguments
def import_animation(target): brres = BrawlAPI.RootNode # verify model exists model_wrapper = None model = None for mdl in BrawlAPI.NodeWrapperListOfType[MDL0Wrapper](): if mdl.Resource.Name == "course": model_wrapper = mdl model = mdl.Resource # verify material exists material = None for mat in model.FindChildrenByType("/", ResourceType.MDL0Material): if mat.Name == target: material = mat if material == None or model_wrapper == None or model == None: return ################ ### Clean Up ### ################ for reference in material.GetChildrenRecursive(): # delete old textures for texture in BrawlAPI.NodeListOfType[TEX0Node](): if texture.Name == reference.Name: texture.Remove(True) # delete old mdl0 texture references for mdl0_tex in BrawlAPI.NodeListOfType[MDL0TextureNode](): if mdl0_tex.Name == reference.Name: mdl0_tex.Remove() # delete old animation for srt in BrawlAPI.NodeListOfType[SRT0Node](): for srt_subnode in srt.Children: if srt_subnode.Name == material.Name: srt.Remove() ################# ### Importing ### ################# for filename in Directory.GetFiles(preset_path): # import textures if filename.endswith(".tex0"): node = NodeFactory.FromFile(None, filename) brres.GetOrCreateFolder[TEX0Node]().AddChild(node) # import material if filename.endswith(".mdl0mat"): material.Replace(filename) material.Name = Path.GetFileNameWithoutExtension(filename) # import shader and set material shader if filename.endswith(".mdl0shade"): # replace shader if only in use by target if len(material.ShaderNode.Materials) == 1: material.ShaderNode.Replace(filename) # otherwise make a new shader else: shader = model_wrapper.NewShader() shader.Replace(filename) material.ShaderNode = shader # import animation and rename material if filename.endswith(".srt0"): node = NodeFactory.FromFile(None, filename) brres.GetOrCreateFolder[SRT0Node]().AddChild(node)
# show output window output.Show() output.WriteLine('Setting temperature to ' + str(temp) + '[*C]') output.WriteLine('Setting humidity to ' + str(hum) + '[%]') output.WriteLine('Setting pressure to ' + str(pres) + '[hPa]') # channel var ch = 0 # iterate over all folders for file in files: ch = ch + 1 # get file paths folder = Path.GetDirectoryName(file) name = Path.GetFileNameWithoutExtension(file) ext = Path.GetExtension(file) newname = folder + '\\' + 'edited_' + str(ch) + '_' + name + ext wave = waves.LoadWave(file) wave.AudioFile.Temperature = temp wave.AudioFile.Humidity = hum wave.AudioFile.Pressure = pres wave.AudioFile.ReceiverNo = ch wave.SaveAs(newname) output.WriteLine('Saving as: ' + newname + ' - ok') wave.Close() # make sure to close the file, otherwise you'll run out of memory output.WriteLine('That\'s all')
# remove leading whitespace from barcode barcode = barcode[1:] return barcode, barcodeinfo, barcode_found # get the active image document activeimage = Zen.Application.Documents.ActiveDocument # read the barcode from the image barcode, barcodeinfo, found = ReadBarCodefromImage(activeimage) print 'Found Barcode : ', found print 'Barcode : ', barcode print 'Barcode Info : ', barcodeinfo if found: # save with new name filename = activeimage.FileName newname = Path.Combine( Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) + '_' + barcode + '.czi') print 'Save with new name : ', newname activeimage.Save(newname) activeimage.Close() if reload: reload_image = Zen.Application.LoadImage(newname, False) Zen.Application.Documents.Add(reload_image) print 'Done.'
# check directory for files to export czidir = Directory.GetFiles(sourcedir, '*.czi') numczi = czidir.Length # this list contains the subdirectories created for splitting splitdirs = [] if split == True: print 'Split CZI using Split Scenes (Write Files): yes' # Batch Loop - Load all CZI images and do Split Scenes (Write Files) for i in range(0, numczi): # get current CZI file czifile = czidir[i] file_woExt = Path.GetFileNameWithoutExtension(czifile) # create separate directory for the current file splitdir = Path.Combine(sourcedir, file_woExt + '_Single') Directory.CreateDirectory(splitdir) # store directory name inside list splitdirs.append(splitdir) print 'File to split: ', czifile image = Zen.Application.LoadImage(czifile, False) # split single CZI file containing all wells into single CZI files Zen.Processing.Utilities.SplitScenes(image, splitdir, ZenCompressionMethod.None, True, True, False) # close file image.Close() print 'Finished Split Scences (Write Files): ', czifile
raise Exception('Execution stopped. Required Columns are missing.') # show and save data tables to the specified folder Zen.Application.Documents.Add(AllObj) Zen.Application.Documents.Add(SingleObj) AllObj.Save(Path.Combine(OutputFolder, 'OverviewTable.csv')) SingleObj.Save(Path.Combine(OutputFolder, 'SingleObjectsTable.csv')) # use APEER module to detect the objects if use_apeer: # read it from settings file ams = ZenApeer.Onsite.ModuleSetting() # loaf the APEER module seeting b - remove *.czams file extension first ams.Load(Path.GetFileNameWithoutExtension(ApeerMS)) print('----- Apeer Module Setting -----') print('Module Name : ', ams.ModuleName) print('Module Version : ', ams.ModuleVersion) print('Module Parameters : ', ams.Parameters) # get module and check mymodule, version_found = get_module(ams.ModuleName, module_version=ams.ModuleVersion) # exit if the check failed if mymodule is None or not version_found: print('Module check failed. Exiting.') raise SystemExit