kidd Posted July 7, 2016 Report Posted July 7, 2016 (edited) Salutare, Incerc sa implementeaz un dialog box pentru selectarea unui working directory pentru un script de Python. As vrea sa fac in asa fel incat scriptul sa nu aiba niciun working directory prestabilit ci sa trebuiasca definit atunci cand e rulat scriptul printr-un un mic dialog box. Asta e scriptul: # import modules import os, numpy, sys, time from osgeo import gdal, ogr from osgeo.gdalconst import * startTime = time.time() # set the working directory os.chdir(r'F:\NDVI_Py\data') # register all of the GDAL drivers gdal.AllRegister() # open the image inDs = gdal.Open('L82015.img', GA_ReadOnly) if inDs is None: print 'Could not open L82015.img' sys.exit(1) # get image size rows = inDs.RasterYSize cols = inDs.RasterXSize bands = inDs.RasterCount # get the bands and block sizes inBand4 = inDs.GetRasterBand(4) inBand5 = inDs.GetRasterBand(5) blockSizes = inBand4.GetBlockSize() xBlockSize = blockSizes[0] yBlockSize = blockSizes[1] # create the output image driver = gdal.GetDriverByName('HFA') outDs = driver.Create('ndvi_L82015.img', cols, rows, 1, GDT_Float32) if outDs is None: print 'Could not create ndvi_L82015.img.img' sys.exit(1) outBand = outDs.GetRasterBand(1) # loop through the rows for i in range(0, rows, yBlockSize): if i + yBlockSize < rows: numRows = yBlockSize else: numRows = rows - i # loop through the columns for j in range(0, cols, xBlockSize): if j + xBlockSize < cols: numCols = xBlockSize else: numCols = cols - j # read the data in data4 = inBand4.ReadAsArray(j, i, numCols, numRows).astype(numpy.float) data5 = inBand5.ReadAsArray(j, i, numCols, numRows).astype(numpy.float) # do the calculations mask = numpy.greater(data4 + data5, 0) ndvi = numpy.choose(mask, (-99, (data5 - data4) / (data5 + data4 + 0.00000000001))) # write the data outBand.WriteArray(ndvi, j, i) # flush data to disk, set the NoData value and calculate stats outBand.FlushCache() outBand.SetNoDataValue(-99) stats = outBand.GetStatistics(0, 1) # georeference the image and set the projection outDs.SetGeoTransform(inDs.GetGeoTransform()) outDs.SetProjection(inDs.GetProjection()) # build pyramids gdal.SetConfigOption('HFA_USE_RRD', 'YES') outDs.BuildOverviews(overviewlist=[2,4,8,16,32,64,128]) inDs = None outDs = None print 'NDVI Calculated and Outputted to File F:\NDVI_Py\data\L82015.img' print 'script took', time.time() - startTime, 'seconds to run' Stiu ca se foloseste tkFileDialog.askdirectory pt asta dar nu stiu cum ar trebui scris in loc de: # set the working directory os.chdir(r'F:\NDVI_Py\data') Apreciez orice sfat. Multumesc! Edited July 7, 2016 by kidd Quote
Active Members MrGrj Posted July 7, 2016 Active Members Report Posted July 7, 2016 (edited) Spoiler 1 hour ago, kidd said: Salutare, Incerc sa implementeaz un dialog box pentru selectarea unui working directory pentru un script de Python. As vrea sa fac in asa fel incat scriptul sa nu aiba niciun working directory prestabilit ci sa trebuiasca definit atunci cand e rulat scriptul printr-un un mic dialog box. Asta e scriptul: # import modules import os, numpy, sys, time from osgeo import gdal, ogr from osgeo.gdalconst import * startTime = time.time() # set the working directory os.chdir(r'F:\NDVI_Py\data') # register all of the GDAL drivers gdal.AllRegister() # open the image inDs = gdal.Open('L82015.img', GA_ReadOnly) if inDs is None: print 'Could not open L82015.img' sys.exit(1) # get image size rows = inDs.RasterYSize cols = inDs.RasterXSize bands = inDs.RasterCount # get the bands and block sizes inBand4 = inDs.GetRasterBand(4) inBand5 = inDs.GetRasterBand(5) blockSizes = inBand4.GetBlockSize() xBlockSize = blockSizes[0] yBlockSize = blockSizes[1] # create the output image driver = gdal.GetDriverByName('HFA') outDs = driver.Create('ndvi_L82015.img', cols, rows, 1, GDT_Float32) if outDs is None: print 'Could not create ndvi_L82015.img.img' sys.exit(1) outBand = outDs.GetRasterBand(1) # loop through the rows for i in range(0, rows, yBlockSize): if i + yBlockSize < rows: numRows = yBlockSize else: numRows = rows - i # loop through the columns for j in range(0, cols, xBlockSize): if j + xBlockSize < cols: numCols = xBlockSize else: numCols = cols - j # read the data in data4 = inBand4.ReadAsArray(j, i, numCols, numRows).astype(numpy.float) data5 = inBand5.ReadAsArray(j, i, numCols, numRows).astype(numpy.float) # do the calculations mask = numpy.greater(data4 + data5, 0) ndvi = numpy.choose(mask, (-99, (data5 - data4) / (data5 + data4 + 0.00000000001))) # write the data outBand.WriteArray(ndvi, j, i) # flush data to disk, set the NoData value and calculate stats outBand.FlushCache() outBand.SetNoDataValue(-99) stats = outBand.GetStatistics(0, 1) # georeference the image and set the projection outDs.SetGeoTransform(inDs.GetGeoTransform()) outDs.SetProjection(inDs.GetProjection()) # build pyramids gdal.SetConfigOption('HFA_USE_RRD', 'YES') outDs.BuildOverviews(overviewlist=[2,4,8,16,32,64,128]) inDs = None outDs = None print 'NDVI Calculated and Outputted to File F:\NDVI_Py\data\L82015.img' print 'script took', time.time() - startTime, 'seconds to run' Stiu ca se foloseste tkFileDialog.askdirectory pt asta dar nu stiu cum ar trebui scris in loc de: # set the working directory os.chdir(r'F:\NDVI_Py\data') Apreciez orice sfat. Multumesc! Ai citit documentatia ? Ai acolo un exemplu cu exact ce iti trebuie: import Tkinter, Tkconstants, tkFileDialog class TkFileDialogExample(Tkinter.Frame): def __init__(self, root): Tkinter.Frame.__init__(self, root) # options for buttons button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5} # define buttons Tkinter.Button(self, text='askopenfile', command=self.askopenfile).pack(**button_opt) Tkinter.Button(self, text='askopenfilename', command=self.askopenfilename).pack(**button_opt) Tkinter.Button(self, text='asksaveasfile', command=self.asksaveasfile).pack(**button_opt) Tkinter.Button(self, text='asksaveasfilename', command=self.asksaveasfilename).pack(**button_opt) Tkinter.Button(self, text='askdirectory', command=self.askdirectory).pack(**button_opt) # define options for opening or saving a file self.file_opt = options = {} options['defaultextension'] = '.txt' options['filetypes'] = [('all files', '.*'), ('text files', '.txt')] options['initialdir'] = 'C:\\' options['initialfile'] = 'myfile.txt' options['parent'] = root options['title'] = 'This is a title' # This is only available on the Macintosh, and only when Navigation Services are installed. #options['message'] = 'message' # if you use the multiple file version of the module functions this option is set automatically. #options['multiple'] = 1 # defining options for opening a directory self.dir_opt = options = {} options['initialdir'] = 'C:\\' options['mustexist'] = False options['parent'] = root options['title'] = 'This is a title' def askopenfile(self): """Returns an opened file in read mode.""" return tkFileDialog.askopenfile(mode='r', **self.file_opt) def askopenfilename(self): """Returns an opened file in read mode. This time the dialog just returns a filename and the file is opened by your own code. """ # get filename filename = tkFileDialog.askopenfilename(**self.file_opt) # open file on your own if filename: return open(filename, 'r') def asksaveasfile(self): """Returns an opened file in write mode.""" return tkFileDialog.asksaveasfile(mode='w', **self.file_opt) def asksaveasfilename(self): """Returns an opened file in write mode. This time the dialog just returns a filename and the file is opened by your own code. """ # get filename filename = tkFileDialog.asksaveasfilename(**self.file_opt) # open file on your own if filename: return open(filename, 'w') def askdirectory(self): """Returns a selected directoryname.""" return tkFileDialog.askdirectory(**self.dir_opt) if __name__=='__main__': root = Tkinter.Tk() TkFileDialogExample(root).pack() root.mainloop() Citeste tot ce acolo, apoi incearca sa implementezi in aplicatia ta ceea ce ai nevoie. Daca nu reusesti, posteaza aici erorile primite si te ajut In fine, mi-e lene sa te ajut mai tarziu. Uite aici ceva rapid: from Tkinter import * import tkFileDialog def askdirectory(): dirname = tkFileDialog.askdirectory() if dirname: var.set(dirname) def UserFileInput(status,name): optionFrame = Frame(root) optionLabel = Label(optionFrame) optionLabel["text"] = name optionLabel.pack(side=LEFT) text = status var = StringVar(root) var.set(text) w = Entry(optionFrame, textvariable= var) w.pack(side = LEFT) optionFrame.pack() return w, var def Print_entry(): print var.get() if __name__ == '__main__': root = Tk() dirBut = Button(root, text='askdirectory', command = askdirectory) dirBut.pack(side = RIGHT) getBut = Button(root, text='print entry text', command = Print_entry) getBut.pack(side = BOTTOM) w, var = UserFileInput("", "Directory") root.mainloop() @fallen_angel tie iti sta in gat daca inveti ? Edited July 7, 2016 by MrGrj 1 Quote
kidd Posted July 7, 2016 Author Report Posted July 7, 2016 (edited) Multumesc! Am vazut dupa editul. Am facut deci un GUI general cu butonul de working directory si scriptul propriu zis: import Tkinter, tkFileDialog, Tkconstants from Tkinter import * root = Tk() root.title('My NDVI GUI') root.geometry('500x100') # Size 500, 200 dirtext='Step 1: Select your working directory!' #Asking directory button def openDirectory(): dirname = tkFileDialog.askdirectory(parent=root, initialdir='/home/', title=dirtext) dirbut["text"] = str(dirname) if dirname else dirtext #Options for button button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5} #Define asking directory button dirbut= Button(root, text = dirtext, bg = 'yellow', fg = 'black', command= openDirectory) dirbut.pack(**button_opt) #Run NDVI def callback(): execfile("example5.py") b=Button(root, text="Step 2: Click for NDVI", command=callback, bg="green") b.pack() root.mainloop() Acum ar fi perfect daca as putea face ca working dir din script sa nu fie definit si sa-mi citeasca directorul ales cu tkfiledialog.askdirectory din GUI. Edited July 7, 2016 by kidd Quote