def select_file(self): from tkfilebrowser import askopenfilenames from tkinter import Tk # Create Tk root root = Tk() # Hide the main window root.withdraw() # Raise the root to the top of all windows. root.call('wm', 'attributes', '.', '-topmost', True) # List of selected filewill be set to self.value ft = self.filetype if ft is not None: if not ft.startswith('.'): ft = '.' + ft name = ft[1:].capitalize() self.files = askopenfilenames( defaultextension=ft, filetypes=[ ('{} file'.format(name),'*{}'.format(ft)), ('All files','*.*')], initialdir=self.initialdir) else: self.files = askopenfilenames() if len(self.files) > 0: self.description = "File Selected" self.icon = "check-square-o" self.style.button_color = "lightgreen" self.value = True else: self.value = False
def askopenfilenames(fd=None, **argv): if fd == None: fd = mode if platform.system() == "Darwin": #load_fd2() return _fd2.askopenfilenames(**argv) if fd: return _fd2.askopenfilenames(**argv) else: return _fd1.askopenfilenames(**argv)
def c_open_file(): rep = askopenfilenames(parent=root, initialdir='/', initialfile='tmp', filetypes=[("Pictures", "*.png|*.jpg|*.JPG"), ("All files", "*")]) print(rep)
def importFromGFile(self): """Attempts to read line by line from GcodeFile at GCodeFilePath and return the read lines as a list. Returns ------- bool True if read from file without an error. list of str A list containing each line read in as a separate str element. """ try: GFilePath = self.dictParams.get("filePath").value print("GFP:" + GFilePath) GFile = fileHandler(fullFilePath=GFilePath) while not GFile.testFileIO('r'): print("\tError opening file... retry selecting GCodeFile:") tkWindow = tk.Tk() GFilePath = askopenfilenames(parent=tkWindow, initialdir='/', initialfile='tmp', filetypes=[("GCode Files", "*.gcode|*.txt"), ("All files", "*")])[0] self.dictParams.get("filePath").value = str(GFilePath) GFile.fullFilePath = str(GFilePath) return GFile.readFullFile() except Exception as inst: print("\tTerminated by Error....") logging.exception(inst)
def importFromGFile(self): """Attempts to read line by line from GcodeFile at GCodeFilePath into memory""" try: GFilePath = self.dictParams.get("filePath").value print("GFP:" + GFilePath) GFile = fileHandler(fullFilePath=GFilePath) while not GFile.testFileIO('r'): print("\tError opening file... retry selecting GCodeFile:") tkWindow = tk.Tk() GFilePath = askopenfilenames(parent=tkWindow, initialdir='/', initialfile='tmp', filetypes=[("GCode Files", "*.gcode|*.txt"), ("All files", "*")])[0] self.dictParams.get("filePath").value = str(GFilePath) GFile.fullFilePath = str(GFilePath) # At this point we have a working file [readStatus, readList] = GFile.readFullFile() if readStatus: return readList else: print("Error reading from file") return False except Exception as inst: print("\tTerminated by Error....") logging.exception(inst) return False
def askfiles(initialdir, title="Séléctionner", **options): """ files selector: initialdir: directory where the filebrowser is opened """ if tkfb: return tkfb.askopenfilenames(title=title, initialdir=initialdir, **options) elif ZENITY: try: args = [ "zenity", "--file-selection", "--filename", initialdir, "--multiple", "--title", title ] files = check_output(args).decode("utf-8").strip() return files.split('|') except CalledProcessError: return "" except Exception: return filedialog.askopenfilenames(title=title, initialdir=initialdir, **options) else: return filedialog.askopenfilenames(title=title, initialdir=initialdir, **options)
def loaddata(): rep = askopenfilenames(initialdir='/', initialfile='tmp', filetypes=[("All files", "*")]) data = pd.read_csv(rep[0]) data.columns = map(str.lower, data.columns) return data
def importFromPCPFile(self): """Attempts to read line by line from PCPCodeFile at PCPCodeFilePath and directly load the read lines into cmdlist Returns ------- bool True if read from file without an error. list list of read in commands as strings """ try: PCPFilePath = self.dictParams.get("filePath").value print("PCPFilePath:" + PCPFilePath) PCPFile = fileHandler(fullFilePath=PCPFilePath) while not PCPFile.testFileIO('r'): print("\tError opening file... retry selecting PCPCodeFile:") tkWindow = tk.Tk() PCPFilePath = askopenfilenames(parent=tkWindow, initialdir='/', initialfile='tmp', filetypes=[("PCPCode Files", "*.PCP|*.txt"), ("All files", "*")])[0] self.dictParams.get("filePath").value = str(PCPFilePath) PCPFile.fullFilePath = str(PCPFilePath) status, inList = PCPFile.readFullFile() return status, inList except Exception as inst: print("\tTerminated by Error....") logging.exception(inst)
def load_texture_map(self): rep = askopenfilenames(parent=self, initialdir='/', initialfile='tmp', filetypes=[("Pictures", "*.png")]) if len(rep) > 0: self.texture_map_path = rep[0] soil_ids_map = Image() soil_ids_map.load_image(self.texture_map_path) self.subplot_texture_map.imshow(soil_ids_map.image) self.canvas_texture_map.draw()
def load_height_map(self): rep = askopenfilenames(parent=self, initialdir='/', initialfile='tmp', filetypes=[("Pictures", "*.png")]) if len(rep) > 0: self.height_map_path = rep[0] image_height_map = Image() image_height_map.load_image(self.height_map_path) self.subplot_height_map.imshow(image_height_map.image, cmap='gray') self.canvas_height_map.draw()
def browse(): View.rep = tkfilebrowser.askopenfilenames( parent=self, initialdir='/', initialfile='tmp', filetypes=[("PDF", "*.pdf"), ["Pictures", "*.png|*.jpg|*.JPG"]]) print(View.rep) label.configure(text=View.rep)
def __init__(self, username, restart=False): self.vsi_img_dir = "../../Input Images/" # where vsi image files are moved to self.archive_dir = "../data/images/" # where we will create and store the .npy archive files fname_dir = "../data/filenames/" self.archives = [ ] # where we will store list of full filepaths for each archive in our archive_dir self.thumbnails = [ ] # where smaller thumbnail image filepaths will be stored username_prefix = "{}_img_".format(username) if restart: """ Loop through all images in img_dir, create enumerated archives for them in archive_dir, and add each enumerated archive filepath to our archives list. """ # Delete all files in the archive directory with the relevant username if restarting clear_dir( self.archive_dir, lambda f: f.split(os.sep)[-1].startswith(username_prefix) and f .split(os.sep)[-1][len(username_prefix):-4].isnumeric()) openslide_image_types = { ".svs", ".tif", ".vms", ".vmu", ".ndpi", ".scn", ".mrxs", ".tiff", ".svslide" } root = Tk() root.title("") selection_filetypes = [ ('Microscopy Images (svs, vsi, czi, png, etc...)', '*.svs|*.tif|*.tiff|*.vms|*.vmu|*.ndpi|*.scn|*.mrxs|*.tiff|*.svslide|*.vsi|*.czi|*.png|*.jpg|' '*.jpeg|*.gif'), ] img_names = list( tkfilebrowser.askopenfilenames(parent=root, title='Select Images to Scan', filetypes=selection_filetypes, initialdir=os.path.join( str(Path.home()), 'Pictures'))) root.destroy() # Name of every image after large images have been split into two # or three constituent images img_names_all = [] vsi_images = [] vsi_png_images = [] for i, name in enumerate(img_names): if name.endswith(".vsi"): folderbase = "_{}_".format('.'.join( os.path.basename(name).split('.')[:-1])) folder_fullname = os.path.join(os.path.dirname(name), folderbase) print(folder_fullname) folder_newpath = os.path.join(self.vsi_img_dir, folderbase) if not os.path.exists(folder_fullname): messagebox.showerror( title="File Not Found", message="No accompanying folder found for {" "}. .vsi files require an " "accompanying folder to display " "the full image.".format(os.path.basename(name))) folder_fullname = None folder_newpath = None vsi_images.append((name, os.path.join(self.vsi_img_dir, os.path.basename(name)), folder_fullname, folder_newpath)) img_names[i] = os.path.join( self.vsi_img_dir, os.path.basename(name)[:-3] + 'png') vsi_png_images.append(img_names[i]) for original_path, new_path, original_folderpath, new_folderpath in vsi_images: # Move vsi files to the # vsi image # directory os.rename(original_path, new_path) if original_folderpath is not None: os.rename(original_folderpath, new_folderpath) if len(vsi_images) > 0: convert_vsi(".png") for original_path, current_path, original_folderpath, current_folderpath in vsi_images: # Move vsi # files # back to their # original directories os.rename(current_path, original_path) if original_folderpath is not None: os.rename(current_folderpath, original_folderpath) # img_names = [name for name in fnames(self.vsi_img_dir, recursive=False)] # Define a callback to be passed to the Asynchronous Progress Bar def archive_callback(index): i = index src_fpath = img_names[i] if not os.path.exists(src_fpath): messagebox.showerror( title="Error", message="Error opening {}: {} does not " "exist.".format(os.path.basename(src_fpath), os.path.basename(src_fpath))) return fname = os.path.basename(src_fpath) sys.stdout.write("\rArchiving Image {}/{}...".format( i + 1, len(img_names))) # Read src, Check max shape, Create archive at dst, add dst to archive list dst_fpath = os.path.join( self.archive_dir, "{}{}.npy".format(username_prefix, len(self.archives))) thumb_fpath = os.path.join( self.archive_dir, "{}{}_thumbnail.npy".format(username_prefix, len(self.archives))) _, src_suffix = os.path.splitext(src_fpath) if src_suffix in openslide_image_types: try: slides = read_openslide_img(src_fpath) except: messagebox.showerror( title="Error", message="Error opening {}: {} is not a valid " "file.".format(os.path.basename(src_fpath), os.path.basename(src_fpath))) return if len(slides) == 2: dst_fpath_a = dst_fpath thumb_fpath_a = thumb_fpath self.archives.append(dst_fpath_a) self.thumbnails.append(thumb_fpath_a) img_names_all.append("{} (1)".format(fname)) dst_fpath_b = os.path.join( self.archive_dir, "{}{}.npy".format(username_prefix, len(self.archives))) thumb_fpath_b = os.path.join( self.archive_dir, "{}{}_thumbnail.npy".format( username_prefix, len(self.archives))) self.archives.append(dst_fpath_b) self.thumbnails.append(thumb_fpath_b) img_names_all.append("{} (2)".format(fname)) slide_npy_a = np.array(slides[0]) slide_npy_b = np.array(slides[1]) thumbnail_a = cv2.resize(slide_npy_a, (0, 0), fx=280 / slide_npy_a.shape[1], fy=280 / slide_npy_a.shape[0]) thumbnail_b = cv2.resize(slide_npy_b, (0, 0), fx=280 / slide_npy_b.shape[1], fy=280 / slide_npy_b.shape[0]) #THUMBNAIL img = cv2.resize(img, dsize=(newsize_y, newsize_x),interpolation=cv2.INTER_CUBIC) np.save(dst_fpath_a, slide_npy_a) np.save(dst_fpath_b, slide_npy_b) np.save(thumb_fpath_a, thumbnail_a) np.save(thumb_fpath_b, thumbnail_b) else: slide_npy = np.array(slides[0]) thumbnail = cv2.resize(slide_npy, (0, 0), fx=280 / slide_npy.shape[1], fy=280 / slide_npy.shape[0]) np.save(dst_fpath, slide_npy) np.save(thumb_fpath, thumbnail) self.archives.append(dst_fpath) self.thumbnails.append(thumb_fpath) img_names_all.append(fname) elif src_suffix == '.vsi': # These should be converted to png before the code gets here return elif src_suffix == '.czi': try: image = czf.imread(src_fpath) except ValueError: messagebox.showerror(title="Error", message="Error opening {}: {} " "is not a valid file.".format( os.path.basename(src_fpath), os.path.basename(src_fpath))) return count = image.shape[0] * image.shape[1] * image.shape[2] for i in range(image.shape[0]): for j in range(image.shape[1]): for k in range(image.shape[2]): # resize_image = cv2.resize(image[i, j, k], dsize=(newsize_y, newsize_x), # interpolation=cv2.INTER_CUBIC) img_npy = np.array(image[i, j, k]) dst_fpath = os.path.join( self.archive_dir, "{}{}.npy".format(username_prefix, len(self.archives))) thumb_fpath = os.path.join( self.archive_dir, "{}{}_thumbnail.npy".format( username_prefix, len(self.archives))) thumbnail = cv2.resize( img_npy, (0, 0), fx=280 / img_npy.shape[1], fy=280 / img_npy.shape[0]) np.save(dst_fpath, img_npy) np.save(thumb_fpath, thumbnail) self.archives.append(dst_fpath) self.thumbnails.append(thumb_fpath) if count > 1: img_names_all.append("{} ({})".format( fname, i * image.shape[1] * image.shape[2] + j * image.shape[2] + k + 1)) else: img_names_all.append(fname) pass else: # Primarily png and other images readable by numpy try: # img_npy = cv2.imread(src_fpath) img_npy = read_image_bgr(src_fpath) except cv2.error as e: messagebox.showerror(title="Error", message="Error opening {}. {}" "file.".format( os.path.basename(src_fpath), e)) if img_npy is None: messagebox.showerror( title="Error", message="Error opening {}. {} is not a valid " "file.".format(os.path.basename(src_fpath), os.path.basename(src_fpath))) return thumbnail = cv2.resize(img_npy, (0, 0), fx=280 / img_npy.shape[1], fy=280 / img_npy.shape[0]) np.save(dst_fpath, img_npy) np.save(thumb_fpath, thumbnail) self.archives.append(dst_fpath) self.thumbnails.append(thumb_fpath) img_names_all.append(fname) # The root process completes the callback's task while keeping track of progress print(len(img_names)) root = ProgressRoot(len(img_names), "Archiving Images", archive_callback) root.mainloop() sys.stdout.flush() print("") if len(self.archives) == 0: messagebox.showerror( title="Error", message= "No images loaded into archive. L.I.R.A. will now exit.") sys.exit(1) # delete excess pngs from vsi conversion for image_file in vsi_png_images: os.remove(image_file) # This collects image resolutions for necessary resizing. This became necessary when # additional image resolutions were being used. # root = Tk() # root.title("Input Image Resolutions") # root.withdraw() # save img names to use in stat output self.fnames = img_names_all with open( os.path.join(fname_dir, '{}_fnames.json'.format(username)), 'w') as f: json.dump(self.fnames, f) archives_with_pathnames = list(zip(self.thumbnails, img_names_all)) img_resolutions = [[0.41, 0.41] for i in archives_with_pathnames] ir = ImageResolutions(archives_with_pathnames, img_resolutions) # ir.resizable(False, False) # img_resolutions = ir.show() # root.destroy() def resize_callback(index): i = index dst_fpath = self.archives[i] # If the defaults haven't been changed, then there is no need to resize. if img_resolutions[i][0] == img_resolutions[i][1] == 0.41: return img = np.load(dst_fpath) newsize_x = int(img.shape[0] / (0.41 / img_resolutions[i][0])) newsize_y = int(img.shape[1] / (0.41 / img_resolutions[i][1])) img = cv2.resize(img, dsize=(newsize_y, newsize_x), interpolation=cv2.INTER_CUBIC) np.save(dst_fpath, img) root = ProgressRoot(len(self.archives), "Resizing Images", resize_callback) root.mainloop() sys.stdout.flush() print("") else: with open( os.path.join(fname_dir, '{}_fnames.json'.format(username)), 'r') as f: self.fnames = json.load(f) # use existing archive files for fname in fnames(self.archive_dir): fn = fname.split(os.sep)[-1] if fn.startswith(username + '_img_' ) and fn[len(username_prefix):-4].isnumeric(): self.archives.append(os.path.join(self.archive_dir, fname)) # Regardless of this we sort the result, since it depends on the nondeterministic ordering of the os.walk # generator in fnames() # We have to get the filename integer number, since otherwise we will end up with stuff like 0, 10, 11, # 1 instead of 0, 1, 10, 11 self.archives = sorted( self.archives, key=lambda x: int(x.split(os.sep)[-1][len(username_prefix):-4]))
def FindHistPeaks(Y): peaks, properties = scipy.signal.find_peaks(Y, width=10, height=5, prominence=2, distance=15) return peaks, properties root = tk.Tk() root.withdraw() print('I owe a million dollars!') FileNames = askopenfilenames(parent=root, initialfile='tmp', filetypes=[("Binary Files", "*.dat")]) with DRS4BinaryFile(FileNames[0]) as events: length = len(list(events)) itertor = 1 GainArray = [] GainErrorArray = [] for i in tqdm(range(len(FileNames)), 'Files', dynamic_ncols=True, unit='Files'): FileName = FileNames[i] directory = os.path.dirname(FileName) newDirectory = os.path.join(directory, FileName[:-4]) path, name = os.path.split(FileName) if not os.path.exists(newDirectory): os.mkdir(newDirectory)
t.append(str(listss[str(int(v))][typee-1])) v += 1 voltage = np.full(((int((listss.shape[0]-datas-typee+types-1)/int(typee-types-1))), 1), 0.00000000000000000000000) capacitance = np.full(((int((listss.shape[0]-datas-typee+types-1)/(typee-types-1))), 1), 0.00000000000000000000000) i = 0 j = int(datas + 2 + int(inx/5)) ## datas + share + 2 k = int(datas + 2 + int(iny/5)) ## datas + share + 2 while i < int(int(listss.shape[0]-datas-typee+types-1)/int(typee-types-1)): voltage[int(i)] = float(listss[str(int(inx%5))][j + i * 3]) capacitance[int(i)] = float(listss[str(int(iny % 5))][k + i * 3]) i = i + 1 s = str(files) plt.plot(voltage, capacitance, label = s.replace('C:\\Users\\DCLAB\\Desktop\\신익\\200526_sim_result\\200526_sim_result\\CV_Dit_Freq_wResult\\200525_CV_Dit_Freq\\','')) plt.xlabel(str(listss[str(int(inx%5))][int(types+2+int(inx/5))])) plt.ylabel(str(listss[str(int(iny%5))][int(types+2+int(iny/5))])) files = tkfilebrowser.askopenfilenames() # files might be "file1.txt file2.exe file3.bmp" at this point a = len(files) c = 0 inx = 0 iny = 0 ########################## CV Plotting #################################### selectplot(files[c],inx,iny) print("X축") inx = int(input()) print("Y축") iny = int(input()) while c < a: openplot(files[c],inx,iny) c = c + 1 plt.legend()