Exemple #1
0
 def reconstructfaces(self, selectedfacesnum):
     recondir = os.path.join(c.DEFAULT_IMAGES_DIR, 'reconfaces')
     newwt=zeros(self.weights.shape)
     eigenfaces=self.bundle.eigenfaces
     usub=eigenfaces[:selectedfacesnum,:]
     evals=self.bundle.evals
     evalssub=evals[:selectedfacesnum]        
     for i in range(len(self.weights)):
         for j in range(len(evalssub)):        
             newwt[i][j]=self.weights[i][j]*evalssub[j]
     phinew=dot(newwt,usub)    
     
     xnew=phinew+self.bundle.avgvals
     if isdir(recondir):
         rmtree(recondir,True)
     mkdir(recondir)
     #print "made:",recondir
     numimgs=len(self.bundle.imglist)
     for x in range(numimgs):
         imgname=recondir+"/reconphi"+str(x)+".png" 
         imgdata=phinew[x]           
         imageops.make_image(imgdata,imgname,(self.bundle.wd,self.bundle.ht),True)
         
     for x in range(numimgs):
         filename=recondir+"/reconx"+str(x)+".png"
         imgdata=xnew[x]
         imageops.make_image(imgdata,filename,(self.bundle.wd,self.bundle.ht),True)
    def reconstructfaces(self, selectedfacesnum):
        #reconstruct
        recondir = '../reconfaces'
        newwt = zeros(self.weights.shape)
        eigenfaces = self.bundle.eigenfaces
        usub = eigenfaces[:selectedfacesnum, :]
        evals = self.bundle.evals
        evalssub = evals[:selectedfacesnum]
        for i in range(len(self.weights)):
            for j in range(len(evalssub)):
                newwt[i][j] = self.weights[i][j] * evalssub[j]
        phinew = dot(newwt, usub)

        xnew = phinew + self.bundle.avgvals
        if isdir(recondir):
            rmtree(recondir, True)
        mkdir(recondir)
        #print "made:",recondir
        print "Elaborando directorio:", recondir
        numimgs = len(self.bundle.imglist)
        for x in range(numimgs):
            imgname = recondir + "/reconphi" + str(x) + ".png"
            imgdata = phinew[x]
            imageops.make_image(imgdata, imgname,
                                (self.bundle.wd, self.bundle.ht), True)

        for x in range(numimgs):
            filename = recondir + "/reconx" + str(x) + ".png"
            imgdata = xnew[x]
            imageops.make_image(imgdata, filename,
                                (self.bundle.wd, self.bundle.ht), True)
Exemple #3
0
 def createEigenimages(self,eigenspace):                
     egndir='../eigenfaces'        
     if isdir(egndir):                
         rmtree(egndir,True)               
     mkdir(egndir)            
     numimgs=len(self.bundle.imglist)
     for x in range(numimgs):
         imgname=egndir+"/eigenface"+str(x)+".png"            
         imageops.make_image(eigenspace[x],imgname,(self.bundle.wd,self.bundle.ht))
Exemple #4
0
 def createEigenimages(self, eigenspace):
     egndir = os.path.join(c.DEFAULT_IMAGES_DIR, 'eigenfaces')
     if isdir(egndir):
         rmtree(egndir,True)
     mkdir(egndir)
     numimgs=len(self.bundle.imglist)
     for x in range(numimgs):
         imgname=egndir+"/eigenface"+str(x)+".png"
         imageops.make_image(eigenspace[x],imgname,(self.bundle.wd,self.bundle.ht))
Exemple #5
0
 def createEigenimages(self,eigenspace):                
     egndir='./tmp/eigenfaces'        
     if isdir(egndir):                
         rmtree(egndir,True)               
     mkdir(egndir)            
     numimgs=len(self.bundle.imglist)
     for x in range(numimgs):
         imgname=egndir+"/eigenface"+str(x)+".png"            
         imageops.make_image(eigenspace[x],imgname,(self.bundle.wd,self.bundle.ht))
Exemple #6
0
	def saveVals(self,selectedfacesnum):
		'''save self.bundle.eigenfaces and self.bundle.avgvals and self.weights'''
		BASE_PATH = os.path.dirname(os.path.realpath(sys.argv[0]))
		for x in range(selectedfacesnum):
			imgname = BASE_PATH + '/eigendata/eigenface' + str(x) + '.png'
			imageops.make_image(self.bundle.eigenfaces[:selectedfacesnum,:][x],imgname,(self.bundle.wd,self.bundle.ht))
		weights = self.createWeightHash()
		pickle.dump(weights,open(BASE_PATH + '/eigendata/weights.db','w'))
		return
Exemple #7
0
 def createEigenimages(self, eigenspace):
     egndir = os.path.join(c.DEFAULT_IMAGES_DIR, 'eigenfaces')
     if isdir(egndir):
         rmtree(egndir, True)
     mkdir(egndir)
     numimgs = len(self.bundle.imglist)
     for x in range(numimgs):
         imgname = egndir + "/eigenface" + str(x) + ".png"
         imageops.make_image(eigenspace[x], imgname,
                             (self.bundle.wd, self.bundle.ht))
 def createFaceBundle(self, imglist):
     """
         Creates a face bundle from the image list
         and saves the eigenface images to the eigenfaces-dir
         @param imglist: list of image filenames
     """
     print "createFaceBundle()"        
     imgfilelist = self.validateDirectory(imglist) # list of XImage
     
     img = imgfilelist[0]
     imgwdth = img._width
     imght = img._height
     numpixels = imgwdth * imght # number of pixels in each image
     numimgs = len(imgfilelist) # total number of images        
     #trying to create a 2d array ,each row holds pixvalues (flat array representation of the image matrix) of a single image
     facemat = zeros((numimgs, numpixels)) # face matrix         
     for i in range(numimgs):
         pixarray = asfarray(imgfilelist[i]._pixellist) # get pixel array of image
         pixarraymax = max(pixarray) # max value in the flat image array
         pixarrayn = pixarray / pixarraymax # normalize array                 
         facemat[i, :] = pixarrayn # set array to correct row in the matrix          
     
     #create average values, one for each column(ie pixel). 
     # each value stands for the average of the pixel in all images, thus we have an array of lenght numpixels  
     avgvals = average(facemat, axis=0)
     #make average faceimage in currentdir just for fun viewing..
     imageops.make_image(avgvals,"average.png",(imgwdth,imght))               
     #substract avg val from each orig val to get adjusted faces(phi of T&P)     
     adjfaces = facemat - avgvals
     adjfaces_tr = adjfaces.transpose()        
     L = dot(adjfaces , adjfaces_tr)
     evals1, evects1 = eigh(L)
     #svd also works..comment out the prev line and uncomment next line to see 
     #evects1,evals1,vt=svd(L,0)        
     reversedevalueorder = evals1.argsort()[::-1]
     evects = evects1[:, reversedevalueorder]               
     evals = sort(evals1)[::-1] # sort the eigen values
     #rows in u are eigenfaces        
     u = dot(adjfaces_tr, evects)
     u = u.transpose()               
     #NORMALISE rows of u
     for i in range(numimgs):
         ui = u[i]
         ui.shape = (imght, imgwdth)
         norm = trace(dot(ui.transpose(), ui))            
         u[i] = u[i] / norm        
     
     self.bundle = FaceBundle(imglist, imgwdth, imght, adjfaces, u, avgvals, evals)
     #print "in facebundle:imgwdth=",imgwdth,"imght=",imght
     self.createEigenimages(u)# eigenface images
    def createFaceBundle(self, imglist):
        imgfilelist = self.validateDirectory(imglist)
        img = imgfilelist[0]
        imgwdth = img._width
        imght = img._height
        numpixels = imgwdth * imght
        numimgs = len(imgfilelist)
        #trying to create a 2d array ,each row holds pixvalues of a single image
        facemat = zeros((numimgs, numpixels))
        for i in range(numimgs):
            pixarray = asfarray(imgfilelist[i]._pixellist)
            pixarraymax = max(pixarray)
            pixarrayn = pixarray / pixarraymax
            facemat[i, :] = pixarrayn

        #create average values ,one for each column(ie pixel)
        avgvals = average(facemat, axis=0)
        #make average faceimage in currentdir just for fun viewing..
        imageops.make_image(avgvals, "average.png", (imgwdth, imght))
        #substract avg val from each orig val to get adjusted faces(phi of T&P)
        adjfaces = facemat - avgvals

        adjfaces_tr = adjfaces.transpose()

        L = dot(adjfaces, adjfaces_tr)

        evals1, evects1 = eigh(L)
        #to use svd ,comment out the previous line and uncomment the next
        #evects1,evals1,vt=svd(L,0)
        reversedevalueorder = evals1.argsort()[::-1]
        evects = evects1[:, reversedevalueorder]
        evals = sort(evals1)[::-1]
        #rows in u are eigenfaces
        u = dot(adjfaces_tr, evects)
        u = u.transpose()
        #NORMALISE rows of u
        for i in range(numimgs):
            ui = u[i]
            ui.shape = (imght, imgwdth)
            norm = trace(dot(ui.transpose(), ui))
            u[i] = u[i] / norm

        self.bundle = FaceBundle(imglist, imgwdth, imght, adjfaces, u, avgvals,
                                 evals)
        self.createEigenimages(u)  # eigenface images
Exemple #10
0
    def createFaceBundle(self,imglist):                
        imgfilelist=self.validateDirectory(imglist)        
        img=imgfilelist[0]
        imgwdth=img._width
        imght=img._height
        numpixels=imgwdth * imght
        numimgs=len(imgfilelist)               
        #trying to create a 2d array ,each row holds pixvalues of a single image
        facemat=zeros((numimgs,numpixels))               
        for i in range(numimgs):
            pixarray=asfarray(imgfilelist[i]._pixellist)
            pixarraymax=max(pixarray)
            pixarrayn=pixarray/pixarraymax                        
            facemat[i,:]=pixarrayn           
        
        #create average values ,one for each column(ie pixel)        
        avgvals=average(facemat,axis=0)        
        #make average faceimage in currentdir just for fun viewing..
        make_image(avgvals,"average.png",(imgwdth,imght))               
        #substract avg val from each orig val to get adjusted faces(phi of T&P)     
        adjfaces=facemat-avgvals        
                
        adjfaces_tr=adjfaces.transpose()
        
        L=dot(adjfaces , adjfaces_tr)

        evals1,evects1=eigh(L)
        #to use svd ,comment out the previous line and uncomment the next
        #evects1,evals1,vt=svd(L,0)        
        reversedevalueorder=evals1.argsort()[::-1]
        evects=evects1[:,reversedevalueorder]               
        evals=sort(evals1)[::-1]                
        #rows in u are eigenfaces        
        u=dot(adjfaces_tr,evects)
        u=u.transpose()               
        #NORMALISE rows of u
        for i in range(numimgs):
            ui=u[i]
            ui.shape=(imght,imgwdth)
            norm=trace(dot(ui.transpose(), ui))            
            u[i]=u[i]/norm        
        
        self.bundle=FaceBundle(imglist,imgwdth,imght,adjfaces,u,avgvals,evals)
        #print "in facebundle:imgwdth=",imgwdth,"imght=",imght
        self.createEigenimages(u)# eigenface images
Exemple #11
0
         imgdata=xnew[x]
         imageops.make_image(imgdata,filename,(self.bundle.wd,self.bundle.ht),True)
 
 def createEigenimages(self,eigenspace):                
     egndir='../eigenfaces'        
     try:
         if isdir(egndir):                
             rmtree(egndir,True)                
     except Exception,inst:
         #print "problem removing dir :",inst.message
         print "problema de la eliminacion de dir :",inst.message        
     mkdir(egndir)            
     numimgs=len(self.bundle.imglist)
     for x in range(numimgs):
         imgname=egndir+"/eigenface"+str(x)+".png"            
         imageops.make_image(eigenspace[x],imgname,(self.bundle.wd,self.bundle.ht))
 
 def checkCache(self,dir,imglist,selectedfacesnum):        
     cachefile=join(dir,"saveddata.cache")
     cache_changed=True
     try:
         f=open(cachefile)
     except IOError:
         #print "no cache file found"
         print "ningun archivo de cache encontrado"                
         self.doCalculations(dir,imglist,selectedfacesnum)
     else:
         self.bundle=pickle.load(f)
         oldlist=self.bundle.imglist
         if(imglist==oldlist):
             #print 'both sets same'
Exemple #12
0
class FaceRec:
    def validateSelectedImage(self, imgname):
        selectimg = imageops.XImage(imgname)
        selectwdth = selectimg._width
        selectht = selectimg._height
        if ((selectwdth != self.bundle.wd) or (selectht != self.bundle.ht)):
            #raise ImageError("select image of matching dimensions !")
            raise ImageError(
                "Seleccionar imagen cuyas dimensiones coincidan !")
        else:
            return selectimg

    def findMatchingImage(self, imagename, selectedfacesnum, thresholdvalue):
        selectimg = self.validateSelectedImage(imagename)
        inputfacepixels = selectimg._pixellist
        inputface = asfarray(inputfacepixels)
        pixlistmax = max(inputface)
        inputfacen = inputface / pixlistmax
        inputface = inputfacen - self.bundle.avgvals
        usub = self.bundle.eigenfaces[:selectedfacesnum, :]
        input_wk = dot(usub, inputface.transpose()).transpose()
        dist = ((self.weights - input_wk)**2).sum(axis=1)
        idx = argmin(dist)
        mindist = sqrt(dist[idx])
        result = ''
        if mindist < 1e-10:
            mindist = 0
        print "mindist:", mindist
        if mindist <= thresholdvalue:
            result = self.bundle.imglist[idx]
        #print "try reconstruction"
        print "reconstruccion"
        self.reconstructFaces(selectedfacesnum)
        return mindist, result

    def doCalculations(self, dir, imglist, selectednumeigenfaces):
        self.createFaceBundle(imglist)
        egfaces = self.bundle.eigenfaces
        adjfaces = self.bundle.adjfaces
        self.weights = self.calculateWeights(egfaces, adjfaces,
                                             selectednumeigenfaces)

        #write to cache #escribir en la memoria cache
        cachefile = join(dir, "saveddata.cache")
        f2 = open(cachefile, "w")
        pickle.dump(self.bundle, f2)
        f2.close()

    def validateDirectory(self, imgfilenameslist):
        if (len(imgfilenameslist) == 0):
            #print "folder empty!"
            print "carpeta vacia!"
            #raise DirError("folder empty!")
            raise DirError("carpeta vacia!")
        imgfilelist = []
        for z in imgfilenameslist:
            img = imageops.XImage(z)
            imgfilelist.append(img)
        sampleimg = imgfilelist[0]
        imgwdth = sampleimg._width
        imght = sampleimg._height
        #check if all images have same dimensions //check si todas las imagenes tienen las mismas dimensiones
        for x in imgfilelist:
            newwdth = x._width
            newht = x._height
            if ((newwdth != imgwdth) or (newht != imght)):
                #raise DirError("select folder with all images of equal dimensions !")
                raise DirError(
                    "selecciona una carpeta con todas las imagenes de dimensiones iguales!"
                )
        return imgfilelist

    def calculateWeights(self, eigenfaces, adjfaces, selectedfacesnum):
        usub = eigenfaces[:selectedfacesnum, :]
        wts = dot(usub, adjfaces.transpose()).transpose()
        return wts

    def createFaceBundle(self, imglist):
        imgfilelist = self.validateDirectory(imglist)

        img = imgfilelist[0]
        imgwdth = img._width
        imght = img._height
        numpixels = imgwdth * imght
        numimgs = len(imgfilelist)
        #trying to create a 2d array ,each row holds pixvalues of a single image
        # tratando de crear una matriz 2D, cada fila tiene valores de pixvalues de una sola imagen
        facemat = zeros((numimgs, numpixels))
        for i in range(numimgs):
            pixarray = asfarray(imgfilelist[i]._pixellist)
            pixarraymax = max(pixarray)
            pixarrayn = pixarray / pixarraymax
            facemat[i, :] = pixarrayn

        #create average values ,one for each column(ie pixel)
        #crear valores medios, uno para cada columna (ie pixel)
        avgvals = average(facemat, axis=0)
        #make average faceimage in currentdir just for fun viewing..
        #imageops.make_image(avgvals,"average.png",(imgwdth,imght))
        #substract avg val from each orig val to get adjusted faces(phi of T&P)

        #hacer faceimage medio en currentdir solo para la visualizacion de la diversion ..
        #restar promedio val val de cada orig llegar caras ajustadas (phi de T & P)
        adjfaces = facemat - avgvals
        adjfaces_tr = adjfaces.transpose()
        L = dot(adjfaces, adjfaces_tr)
        evals1, evects1 = eigh(L)
        #svd also works..comment out the prev line and uncomment next line to see
        #Tambien #svd works..comment la linea anterior y elimine el comentario siguiente linea para ver
        #evects1,evals1,vt=svd(L,0)

        reversedevalueorder = evals1.argsort()[::-1]
        evects = evects1[:, reversedevalueorder]
        evals = sort(evals1)[::-1]
        #rows in u are eigenfaces
        #filas de u son Eigenfaces
        u = dot(adjfaces_tr, evects)
        u = u.transpose()
        #NORMALISE rows of u
        for i in range(numimgs):
            ui = u[i]
            ui.shape = (imght, imgwdth)
            norm = trace(dot(ui.transpose(), ui))
            u[i] = u[i] / norm

        self.bundle = FaceBundle(imglist, imgwdth, imght, adjfaces, u, avgvals,
                                 evals)
        self.createEigenimages(u)  # eigenface images

    def reconstructFaces(self, selectedfacesnum):
        recondir = '../reconfaces'
        newwt = zeros(self.weights.shape)
        eigenfaces = self.bundle.eigenfaces
        usub = eigenfaces[:selectedfacesnum, :]
        evals = self.bundle.evals
        evalssub = evals[:selectedfacesnum]
        for i in range(len(self.weights)):
            for j in range(len(evalssub)):
                newwt[i][j] = self.weights[i][j] * evalssub[j]
        phinew = dot(newwt, usub)

        xnew = phinew + self.bundle.avgvals
        try:
            if isdir(recondir):
                rmtree(recondir, True)
        except Exception, inst:
            #print "problem removing dir :",inst.message
            print "problema de la eliminacion de dir :", inst.message
        mkdir(recondir)
        print "made:", recondir
        numimgs = len(self.bundle.imglist)
        for x in range(numimgs):
            imgname = recondir + "/reconphi" + str(x) + ".png"
            imgdata = phinew[x]
            imageops.make_image(imgdata, imgname,
                                (self.bundle.wd, self.bundle.ht), True)

        for x in range(numimgs):
            filename = recondir + "/reconx" + str(x) + ".png"
            imgdata = xnew[x]
            imageops.make_image(imgdata, filename,
                                (self.bundle.wd, self.bundle.ht), True)
Exemple #13
0
            imageops.make_image(imgdata, filename,
                                (self.bundle.wd, self.bundle.ht), True)

    def createEigenimages(self, eigenspace):
        egndir = '../eigenfaces'
        try:
            if isdir(egndir):
                rmtree(egndir, True)
        except Exception, inst:
            #print "problem removing dir :",inst.message
            print "problema de la eliminacion de dir :", inst.message
        mkdir(egndir)
        numimgs = len(self.bundle.imglist)
        for x in range(numimgs):
            imgname = egndir + "/eigenface" + str(x) + ".png"
            imageops.make_image(eigenspace[x], imgname,
                                (self.bundle.wd, self.bundle.ht))

    def checkCache(self, dir, imglist, selectedfacesnum):
        cachefile = join(dir, "saveddata.cache")
        cache_changed = True
        try:
            f = open(cachefile)
        except IOError:
            #print "no cache file found"
            print "ningun archivo de cache encontrado"
            self.doCalculations(dir, imglist, selectedfacesnum)
        else:
            self.bundle = pickle.load(f)
            oldlist = self.bundle.imglist
            if (imglist == oldlist):
                #print 'both sets same'