Beispiel #1
0
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'
Beispiel #2
0
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'
Beispiel #3
0
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
Beispiel #4
0
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
Beispiel #5
0
 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())
Beispiel #6
0
 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())
Beispiel #7
0
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()
Beispiel #8
0
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
Beispiel #9
0
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
Beispiel #10
0
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)
Beispiel #11
0
    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")
f.close()
Beispiel #12
0
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'
Beispiel #13
0
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'
Beispiel #14
0
#        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
for i in xrange(clusters+1):
	indices = np.where(isoarr == i)[0]
	if indices.size:
		clusteredArray[indices] = colorArray[i]
Beispiel #15
0
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)