def bandChoose(): global guiSpat3 guiSpat3=tk.Frame(guiSpat) if(fileName == ''): tkMessageBox.showerror("Error", "Please select an image.") open() return else: if(opt1.get()=='' and opt2.get()==''): tkMessageBox.showerror("Error", "Please select an option.") return elif(opt1.get()!='' and opt2.get()!=''): tkMessageBox.showerror("Error", "Please select only one option.") return else: global box dataset = tifwork.openTIF(fileName) (cols,rows,bands,bandArray) = tifwork.detailsTIF(dataset) optionList=[] for k in range(1, bands+1): optionList.append(k) lab=tk.Label(guiSpat3, text="Band Number : ") lab.pack(side=tk.LEFT, padx=2, pady=2) box= ttk.Combobox(guiSpat3,values=optionList, width=5) box.pack(side = tk.LEFT , pady = 5,padx = 5 ) button=tk.Button(guiSpat3, text="Go", command=goSpatial) button.pack(side=tk.RIGHT, padx=2, pady=2) guiSpat3.pack(side=tk.TOP)
def getData(fileName, num): #get dataset global bandArray global bands global target global data dataset = tifwork.openTIF(fileName) #get details of dataset (cols,rows,bands,bandArray) = tifwork.detailsTIF(dataset) #get all bands bandArray = tifwork.getBand(dataset,bands,bandArray) #input a band print rows, cols workData = bandArray[:,:,num-1] if (data == None): data = np.array([]).reshape(0,bands) target = np.array([]) #show original image and plot it imdata = Image.fromarray(workData) imdata = imdata.convert('L') imdata.save('original.jpg') #plot(workData,'Original') filename = 'original.jpg' return filename
def isoclass(filename, colorArray, x): dataset = tifwork.openTIF(filename) (cols, rows, bands, bandArr) = tifwork.detailsTIF(dataset) bandArr = tifwork.getBand(dataset, bands, bandArr) imageArray = np.array(bandArr, dtype=float) isoarr = isodata_classification(imageArray, x) print isoarr.shape #print rows #colorArray=np.array([[0,0,100],[100,0,0],[0,100,0],[100,100,0],[75,75,75],[0,100,100],[100,0,100],[50,25,25],[25,50,25],[25,25,50]]) clusteredArray = np.zeros((rows * cols, 3)) print clusteredArray.shape clusters = isoarr.max() #print clusters for i in xrange(clusters + 1): indices = np.where(isoarr == i)[0] if indices.size: clusteredArray[indices] = colorArray[i] clusteredArray = clusteredArray.reshape(rows, cols, 3) #print clusteredArray scipy.misc.imsave('iso.jpg', clusteredArray) imageGUI.imdisplay('iso.jpg', 'ISODATA-Image') print 'iso done'
def kmea(colorArray, iterations, fileName): print 'Kmeans' print colorArray print iterations print fileName dataset = tifwork.openTIF(fileName) (cols, rows, bands, bandArr) = tifwork.detailsTIF(dataset) bandArr = tifwork.getBand(dataset, bands, bandArr) imageArray = np.array(bandArr, dtype=float) clusters = len(colorArray) print 'clusters = ', clusters #iterations = 3 (clusterNumber, colorArr) = kmeans(imageArray, clusters, iterations) #print colorArray.shape #print clusterNumber clusteredArray = np.zeros((rows, cols, 3)) for i in range(clusters): index = clusterNumber == i clusteredArray[index] = colorArray[i] scipy.misc.imsave('kMeans.jpg', clusteredArray) imageGUI.imdisplay('kMeans.jpg', 'Kmeans-Image') print 'kmeans done'
def rgbselect(): fileName = tkFileDialog.askopenfilename() if (fileName == ''): pass else: print(fileName) dataset = (tifwork.openTIF(fileName)) w = tk.Tk() def bandPrint(): if (not (opt1.get() and opt2.get() and opt3.get())): showerror("Error", "All bands not selected") elif (opt1.get() == opt2.get() or opt1.get() == opt3.get() or opt2.get() == opt3.get()): showerror("Error", "Two same bands selected") else: bandArr = tifwork.getBand(dataset, bands, bandArray) tifwork.selectBand(bandArr, rows, cols, opt1.get(), opt2.get(), opt3.get()) frame4 = tk.Frame(w) # frame4.grid() frame2 = tk.Frame(frame4) # frame2.grid() frame3 = tk.Frame(frame4) # frame3.grid() frame5 = tk.Frame(w) # frame5.grid() w.title("Band Selection") (cols, rows, bands, bandArray) = tifwork.detailsTIF(dataset) optionList = [] for k in range(1, bands + 1): optionList.append(k) x1 = tk.Label(frame2, text="Red") x1.pack(side=tk.TOP, pady=5, padx=5) opt1 = ttk.Combobox(frame3, values=optionList, width=5) opt1.pack(side=tk.TOP, pady=5, padx=5) x2 = tk.Label(frame2, text="Blue") x2.pack(side=tk.TOP, pady=5, padx=5) opt2 = ttk.Combobox(frame3, values=optionList, width=5) opt2.pack(side=tk.TOP, pady=5, padx=5) x3 = tk.Label(frame2, text="Green") x3.pack(side=tk.TOP, pady=5, padx=5) opt3 = ttk.Combobox(frame3, values=optionList, width=5) opt3.pack(side=tk.TOP, pady=5, padx=5) frame2.pack(side=tk.LEFT, pady=5, padx=5) frame3.pack(side=tk.LEFT, pady=5, padx=5) frame4.pack(side=tk.TOP, pady=5, padx=5) button = tk.Button(frame5, width=10, text="Show", command=bandPrint) button.pack(side=tk.TOP, pady=5, padx=5) frame5.pack(side=tk.TOP, pady=5, padx=5)
def getData(fileName, num): #get dataset global bandArray global bands global target global data dataset = tifwork.openTIF(fileName) #get details of dataset (cols, rows, bands, bandArray) = tifwork.detailsTIF(dataset) #get all bands bandArray = tifwork.getBand(dataset, bands, bandArray) #input a band print rows, cols workData = bandArray[:, :, num - 1] if (data == None): data = np.array([]).reshape(0, bands) target = np.array([]) #show original image and plot it imdata = Image.fromarray(workData) imdata = imdata.convert('L') imdata.save('original.jpg') #plot(workData,'Original') filename = 'original.jpg' return filename
def rgbselect(): fileName=tkFileDialog.askopenfilename() if(fileName == ''): pass else: print(fileName) dataset=(tifwork.openTIF(fileName)) w=tk.Tk() def bandPrint(): if(not(opt1.get() and opt2.get() and opt3.get())): showerror("Error", "All bands not selected") elif(opt1.get()==opt2.get() or opt1.get()==opt3.get() or opt2.get()==opt3.get()): showerror("Error", "Two same bands selected") else: bandArr = tifwork.getBand(dataset,bands,bandArray) tifwork.selectBand(bandArr,rows,cols,opt1.get(),opt2.get(),opt3.get()) frame4 = tk.Frame(w) # frame4.grid() frame2=tk.Frame(frame4) # frame2.grid() frame3=tk.Frame(frame4) # frame3.grid() frame5 = tk.Frame(w) # frame5.grid() w.title("Band Selection") (cols,rows,bands,bandArray) = tifwork.detailsTIF(dataset) optionList=[] for k in range(1, bands+1): optionList.append(k) x1=tk.Label(frame2, text="Red") x1.pack(side=tk.TOP, pady = 5 , padx = 5 ) opt1= ttk.Combobox(frame3,values=optionList, width=5) opt1.pack(side = tk.TOP , pady = 5,padx = 5 ) x2=tk.Label(frame2, text="Blue") x2.pack(side = tk.TOP , pady = 5 , padx = 5 ) opt2= ttk.Combobox(frame3 , values=optionList, width=5) opt2.pack(side = tk.TOP , pady = 5 , padx = 5 ) x3=tk.Label(frame2, text="Green") x3.pack(side = tk.TOP , pady = 5 , padx = 5 ) opt3= ttk.Combobox(frame3, values=optionList, width=5) opt3.pack(side = tk.TOP , pady = 5 , padx = 5 ) frame2.pack(side=tk.LEFT, pady = 5 , padx = 5 ) frame3.pack(side=tk.LEFT, pady = 5 , padx = 5 ) frame4.pack(side= tk.TOP, pady = 5 , padx = 5 ) button = tk.Button(frame5, width=10, text="Show", command=bandPrint) button.pack(side = tk.TOP , pady = 5 , padx = 5 ) frame5.pack(side=tk.TOP , pady = 5 , padx = 5 )
def rgbselect2(): fileName=tkFileDialog.askopenfilename(title='select image to be rectified') if(fileName == ''): pass else: print(fileName) im=(tifwork.openTIF(fileName))
def fuzz(color,filename): #filename = 'liss4.tif' dataset = tw.openTIF(filename) cols, rows,bands,bandArray = tw.detailsTIF(dataset) bandArray = tw.getBand(dataset,bands,bandArray) intBandArray = np.array(bandArray,dtype = float) c = len(color) #print bands #print intBandArray.shape scipy.misc.imsave('hello.jpg',intBandArray) #(L, C, U, LUT, H) = FastFCMeans(intBandArray,c,q) (L,C,U,LUT,H) = ffc.FastFCMeans(intBandArray[:,:,0],c,2) im = intBandArray[:,:,0] #Visualize the fuzzy membership functions plt.figure('Fig 1') #plt.subplot(2,1,1) #Visualize the segmentation Lrgb = np.zeros((np.size(L),3),'uint8') Lflat = L.ravel() Lflat = Lflat[:,np.newaxis] #correct things from here #color = [(0,255,0),(0,0,255),(255,0,0),(0,0,0),(255,255,255),(34,65,0),(0,45,87),(100,100,100),(50,50,50),(12,54,77),(43,65,99)] for i in range(0,c): (temp,b) =np.nonzero(Lflat == i) Lrgb[temp] = color[i] #print im.shape Lrgb = np.reshape(Lrgb,(im.shape)+(3,)) imArray = np.copy(Lrgb.astype('uint8')) print imArray.shape scipy.misc.imsave('1.jpg',imArray) plt.imshow(imArray) plt.show()
def goSpectral(x): global fileName if(fileName == ''): tkMessageBox.showerror("Error", "Please select an image.") open() return else: dic = { 1: PCA.pca , 2: spec.spec , 3: spec.spec , 4: spec.spec} if (x == 1): dic[x](fileName) else: def indices(): i = opt1.get() j = int(i) i = opt2.get() k = int(i) frameSpec1.destroy() frameSpec2.destroy() frameSpec3.destroy() dic[x](fileName,x-1,j,k) frameSpec1=tk.Frame(frameSpec) frameSpec2=tk.Frame(frameSpec) frameSpec1.pack() frameSpec2.pack() frameSpec3= tk.Frame(guiSpec) frameSpec3.pack() dataset = tifwork.openTIF(fileName) (cols,rows,bands,bandArray) = tifwork.detailsTIF(dataset) optionList=[] for k in range(1, bands+1): optionList.append(k) lab1=tk.Label(frameSpec1, text="Band Number 1: ") lab1.pack(side=tk.LEFT, padx=2, pady=2) opt1= ttk.Combobox(frameSpec1,values=optionList, width=5) opt1.pack(side = tk.LEFT , pady = 5,padx = 5 ) lab2=tk.Label(frameSpec2, text="Band Number 2: ") lab2.pack(side=tk.LEFT, padx=2, pady=2) opt2= ttk.Combobox(frameSpec2,values=optionList, width=5) opt2.pack(side = tk.LEFT , pady = 5,padx = 5 ) button=tk.Button(frameSpec3, text="Go", command=indices) button.pack(side=tk.BOTTOM, padx=2, pady=2)
def openref(): selection=" " fileName=tkFileDialog.askopenfilename(title='select reference image') if(fileName == ''): pass else: print(fileName) im=(tifwork.openTIF(fileName)) def sel(): selection =str(var.get()) print selection def printEntry(): print selection a=tk.Tk() a.title('Choose Polynomial order') a.geometry('500x500') var = IntVar() R1 = Radiobutton(a, text="Order 0", variable=var, value=0,command=sel) R1.pack( anchor = W ) R2 = Radiobutton(a, text="Order 1", variable=var, value=1,command=sel) R2.pack( anchor = W ) R3 = Radiobutton(a, text="Order 2", variable=var, value=2,command=sel) R3.pack( anchor = W) label = Label(a) label.pack() L1 = Label(a, text="other") L1.pack( side = LEFT) E1 = Entry(a, bd =5, command=printEntry) E1.pack(side = RIGHT) selection=E1.get() a.mainloop() image=Image.open(im) image1=ImageTk.PhotoImage(image) imagesprite=c.create_image(500,500,image=image1) return im
def getData(fileName, num): #get dataset dataset = tifwork.openTIF(fileName) #get details of dataset (cols, rows, bands, bandArray) = tifwork.detailsTIF(dataset) #get all bands bandArray = tifwork.getBand(dataset, bands, bandArray) #input a band workData = bandArray[:, :, num - 1] #show original image and plot it imdata = Image.fromarray(workData) imdata = imdata.convert('L') imdata.save('original.jpg') #plot(workData,'Original') filename = 'original.jpg' return filename
def getData(fileName, num): #get dataset dataset = tifwork.openTIF(fileName) #get details of dataset (cols,rows,bands,bandArray) = tifwork.detailsTIF(dataset) #get all bands bandArray = tifwork.getBand(dataset,bands,bandArray) #input a band workData = bandArray[:,:,num-1] #show original image and plot it imdata = Image.fromarray(workData) imdata = imdata.convert('L') imdata.save('original.jpg') #plot(workData,'Original') filename = 'original.jpg' return filename
def pca(fileName): dataset = tw.openTIF(fileName) cols, rows,bands,bandArray = tw.detailsTIF(dataset) bandArray = tw.getBand(dataset,bands,bandArray) print bands for i in range(0,bands): array = bandArray[:,:,i] #print array scipy.misc.imsave('./temp/PCA/test'+str(i)+'.png',array) imlist = [] for i in range(0,bands): imlist.append('./temp/PCA/test'+str(i)+'.png') print imlist def pca(X): # Principal Component Analysis # input: X, matrix with training data as flattened arrays in rows # return: projection matrix (with important dimensions first), # variance and mean #get dimensions num_data,dim = X.shape #center data mean_X = X.mean(axis=0) for i in range(num_data): X[i] -= mean_X if dim>100: print 'PCA - compact trick used' M = dot(X,X.T) #covariance matrix print M e,EV = linalg.eigh(M) #eigenvalues and eigenvectors print e print EV tmp = dot(X.T,EV).T #this is the compact trick V = tmp[::-1] #reverse since last eigenvectors are the ones we want S = sqrt(e)[::-1] #reverse since eigenvalues are in increasing order else: print 'PCA - SVD used' U,S,V = linalg.svd(X) V = V[:num_data] #only makes sense to return the first num_data #return the projection matrix, the variance and the mean return V,S,mean_X im = numpy.array(Image.open(imlist[0])) #open one image to get the size m,n = im.shape[0:2] #get the size of the images imnbr = len(imlist) #get the number of images #create matrix to store all flattened images immatrix = numpy.array([numpy.array(Image.open(imlist[i])).flatten() for i in range(imnbr)],'f') #perform PCA V,S,immean = pca(immatrix) #mean image and first mode of variation immean = immean.reshape(m,n) for i in range (0,bands): mode = V[i].reshape(m,n) scipy.misc.imsave('./temp/PCA/pca'+str(i+1)+'.png',mode) x = imageGUI.imdisplay('./temp/PCA/pca'+str(i+1)+'.png','PCA '+str(i),1) #show the images scipy.misc.imsave('./temp/PCA/meanimage.png',immean) imageGUI.imdisplay('./temp/PCA/meanimage.png','Mean Image',1)
from matplotlib.backend_bases import key_press_handler import matplotlib.pyplot as plt import matplotlib.image as mpimg from matplotlib.figure import Figure import pylab #import Image, ImageTk #import tktable import tifwork import matplotlib.gridspec as gridspec fileName = tkFileDialog.askopenfilename(filetypes=[('TIF', '*.tif')]) if (fileName == ''): pass else: print(fileName) dataset = (tifwork.openTIF(fileName)) def histeq(im, nbr_bins=256): # get image histogram imhist, bins = histogram(im.flatten(), nbr_bins, normed=True) cdf = imhist.cumsum() # cumulative distribution function cdf = 255 * cdf / cdf[-1] # normalize # use linear interpolation of cdf to find new pixel values im2 = interp(im.flatten(), bins[:-1], cdf) return im2.reshape(im.shape), cdf def showallhist(imgname):
k , bands = centers.shape ############################################################################### if quit_low_change_in_clusters(centers, last_centers, iter): break # take_snapshot(img_class_flat.reshape(N, M), iteration_step=iter) ############################################################################### print "Isodata(info): Finished with %s classes" % k print "Isodata(info): Number of Iterations: %s" % (iter + 1) return img_class_flat filename = 'liss2.tif' dataset = tifwork.openTIF(filename) (cols,rows,bands,bandArr) = tifwork.detailsTIF(dataset) bandArr = tifwork.getBand(dataset,bands,bandArr) imageArray = np.array(bandArr,dtype =float) x = {'K':5 , 'I':200} isoarr = isodata_classification(imageArray,x) #print rows colorArray=np.array([[0,0,100],[100,0,0],[0,100,0],[100,100,0],[75,75,75],[0,100,100],[100,0,100],[50,25,25],[25,50,25],[25,25,50]]) clusteredArray = np.zeros((rows*cols,3)) clusters = isoarr.max() #print clusters
def pca(fileName): dataset = tw.openTIF(fileName) cols, rows, bands, bandArray = tw.detailsTIF(dataset) bandArray = tw.getBand(dataset, bands, bandArray) print bands for i in range(0, bands): array = bandArray[:, :, i] #print array scipy.misc.imsave('./temp/PCA/test' + str(i) + '.png', array) imlist = [] for i in range(0, bands): imlist.append('./temp/PCA/test' + str(i) + '.png') print imlist def pca(X): # Principal Component Analysis # input: X, matrix with training data as flattened arrays in rows # return: projection matrix (with important dimensions first), # variance and mean #get dimensions num_data, dim = X.shape #center data mean_X = X.mean(axis=0) for i in range(num_data): X[i] -= mean_X if dim > 100: print 'PCA - compact trick used' M = dot(X, X.T) #covariance matrix print M e, EV = linalg.eigh(M) #eigenvalues and eigenvectors print e print EV tmp = dot(X.T, EV).T #this is the compact trick V = tmp[:: -1] #reverse since last eigenvectors are the ones we want S = sqrt(e)[:: -1] #reverse since eigenvalues are in increasing order else: print 'PCA - SVD used' U, S, V = linalg.svd(X) V = V[:num_data] #only makes sense to return the first num_data #return the projection matrix, the variance and the mean return V, S, mean_X im = numpy.array(Image.open(imlist[0])) #open one image to get the size m, n = im.shape[0:2] #get the size of the images imnbr = len(imlist) #get the number of images #create matrix to store all flattened images immatrix = numpy.array( [numpy.array(Image.open(imlist[i])).flatten() for i in range(imnbr)], 'f') #perform PCA V, S, immean = pca(immatrix) #mean image and first mode of variation immean = immean.reshape(m, n) for i in range(0, bands): mode = V[i].reshape(m, n) scipy.misc.imsave('./temp/PCA/pca' + str(i + 1) + '.png', mode) x = imageGUI.imdisplay('./temp/PCA/pca' + str(i + 1) + '.png', 'PCA ' + str(i), 1) #show the images scipy.misc.imsave('./temp/PCA/meanimage.png', immean) imageGUI.imdisplay('./temp/PCA/meanimage.png', 'Mean Image', 1)
(at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import numpy as np from osgeo import gdal import tifwork dataset = tifwork.openTIF(filename) cols, rows, bands, bandArray = tifwork.detailsTIF(dataset) bandArray = tifwork.getBand(dataset, bands, bandArray) mean = np.mean(bandArray, axis=0) median = np.median(bandArray, axis=0) stddev = np.std(bandArray, axis=0) max = np.max(bandArray, axis=0) min = np.min(bandArray, axis=0) f = open("abc.txt", 'w') f.write("Mean = " + str(mean) + "\n") f.write("Median = " + str(median) + "\n") f.write("Standard Deviation = " + str(stddev) + "\n") f.write("Max = " + str(max) + "\n") f.write("Min = " + str(min) + "\n")
def svmwork(fileName,data,target,typ): print 'SVM' dataset = tifwork.openTIF(fileName) (cols,rows,bands,bandArr) = tifwork.detailsTIF(dataset) bandArr = tifwork.getBand(dataset,bands,bandArr) imageArray = np.array(bandArr,dtype =float) print imageArray.shape array = imageArray.copy() array = array.reshape((cols*rows),bands) #print array.shape # training data extract # classifying training data #print target.shape #print data.shape #print array.shape # SVM if (typ == 'poly'): clf = svm.SVC(kernel=typ,degree=3) else: clf = svm.SVC(kernel=typ) clf.fit(data, target) isoarr = clf.predict(array) isoarr = np.array(isoarr,dtype =int) #print isoarr #print isoarr.max() #print z.shape #print z colorArray=np.array([[0,0,100],[100,0,0],[0,100,0],[100,100,0],[75,75,75],[0,100,100],[100,0,100],[50,25,25],[25,50,25],[25,25,50]]) clusteredArray = np.zeros((rows*cols,3)) #print clusteredArray.shape clusters = isoarr.max() #print clusters for i in xrange(clusters+1): indices = np.where(isoarr == i)[0] print i ,indices.size if indices.size: clusteredArray[indices] = colorArray[i] print clusteredArray clusteredArray = clusteredArray.reshape(rows,cols,3) #print clusteredArray scipy.misc.imsave('svm'+typ+'.jpg',clusteredArray) imageGUI.imdisplay('svm'+typ+'.jpg','SVM-'+typ+'-Image') print 'SVM Done'
def svmwork(fileName, data, target, typ): print 'SVM' dataset = tifwork.openTIF(fileName) (cols, rows, bands, bandArr) = tifwork.detailsTIF(dataset) bandArr = tifwork.getBand(dataset, bands, bandArr) imageArray = np.array(bandArr, dtype=float) print imageArray.shape array = imageArray.copy() array = array.reshape((cols * rows), bands) #print array.shape # training data extract # classifying training data #print target.shape #print data.shape #print array.shape # SVM if (typ == 'poly'): clf = svm.SVC(kernel=typ, degree=3) else: clf = svm.SVC(kernel=typ) clf.fit(data, target) isoarr = clf.predict(array) isoarr = np.array(isoarr, dtype=int) #print isoarr #print isoarr.max() #print z.shape #print z colorArray = np.array([[0, 0, 100], [100, 0, 0], [0, 100, 0], [100, 100, 0], [75, 75, 75], [0, 100, 100], [100, 0, 100], [50, 25, 25], [25, 50, 25], [25, 25, 50]]) clusteredArray = np.zeros((rows * cols, 3)) #print clusteredArray.shape clusters = isoarr.max() #print clusters for i in xrange(clusters + 1): indices = np.where(isoarr == i)[0] print i, indices.size if indices.size: clusteredArray[indices] = colorArray[i] print clusteredArray clusteredArray = clusteredArray.reshape(rows, cols, 3) #print clusteredArray scipy.misc.imsave('svm' + typ + '.jpg', clusteredArray) imageGUI.imdisplay('svm' + typ + '.jpg', 'SVM-' + typ + '-Image') print 'SVM Done'
from matplotlib.figure import Figure import pylab #import Image, ImageTk #import tktable import tifwork import matplotlib.gridspec as gridspec fileName=tkFileDialog.askopenfilename(filetypes=[('TIF','*.tif')]) if(fileName == ''): pass else: print(fileName) dataset=(tifwork.openTIF(fileName)) def histeq(im,nbr_bins=256): # get image histogram imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) cdf = imhist.cumsum() # cumulative distribution function cdf = 255 * cdf / cdf[-1] # normalize # use linear interpolation of cdf to find new pixel values im2 = interp(im.flatten(),bins[:-1],cdf) return im2.reshape(im.shape), cdf def showallhist(imgname):