VGGFace python 抽取人脸特征

来源:互联网 发布:淘宝抢月饼 编辑:程序博客网 时间:2024/05/29 15:21

“`

import numpy,cv2
import os,caffe
import sklearn.metrics.pairwise as pw
import time,skimage
import matplotlib.pyplot as plt
import numpy as np
class LightCNN():
def init(self, end_cnn=”eltwise_fc1”, model_version=”LightenedCNN_B”):
self.net = caffe.Net(“VGG_FACE_deploy.prototxt”,”VGG_FACE.caffemodel”, caffe.TEST) #load net
self.end_cnn=”fc7”
self.model_version = model_version

def getFeat(self, imgPath):    '''    img = caffe.io.load_image(imgPath,color=False)    img = skimage.img_as_float(skimage.io.imread(imgPath, as_grey=not False)).astype(np.float32)    if img.ndim == 2:      print "img.ndim =sss= 2"      img = img[:, :, np.newaxis]    #img = cv2.imread(imgPath,0)    print "img.ndim===<<><<" + str(img.ndim)    img = cv2.resize(img,(128,128))    print img.shape    #img.convertTo(img, cv2.CV_32FC1);    #img = img.reshape(128,128)    assert img.ndim == 2    #assert img.max() <= 1.001    h, w = img.shape    assert h == w == 128    formatted_image = numpy.reshape(img, (1, 1, h, w)).astype(float)    output = self.net.forward([self.end_cnn], data=formatted_image)    return output[self.end_cnn].copy().flatten()    averageImg = [129.1863,104.7624,93.5940]    image = caffe.io.load_image( "ak.png" ) #RGB    #img = cv2.imread("ak.png" )    #plt.imshow(img)    #plt.show()    #cv2.imshow("img",img)    #cv2.waitKey(0)     #img = img[:,:,::-1]*255.0 # convert RGB->BGR    R = image[0, :, :] - averageImg[0]    G = image[1, :, :] - averageImg[1]    B = image[2, :, :] - averageImg[2]    bgr_image = numpy.zeros(shape=image.shape)    bgr_image[0, :, :] = B    bgr_image[1, :, :] = G    bgr_image[2, :, :] = R    '''    #image = caffe.io.load_image( "ak.png" )    #image = image[:,:,::-1]*255.0 # convert RGB->BGR    image = cv2.imread("q1.jpg" )  #opencv is BRG    avg = np.array([93.5940,104.7624,129.1863]) #substract by BGR    image = image - avg # subtract mean (numpy takes care of dimensions :)    #img = img - avg # subtract mean (numpy takes care of dimensions :)    image = image.transpose((2,0,1))  ## equal to permute    image = image[None,:] # add singleton dimension    out = self.net.forward([self.end_cnn], data=image)    return out['fc7']    #labels=np.loadtxt('names.txt',str,delimiter='\n') # get the name    #print labels[out['prob'].argmax()]

cnn = LightCNN()

for r in [i/10.0 for i in range(10)]:

#print r
imgPath = “ak.png”
t1 = time.time()
feat = cnn.getFeat(imgPath)

for f in feat:
for i in f:
print i

”’
feat2 = cnn.getFeat(“E://19.jpg”)

print (feat)

t2 = time.time()

print len(feat),t2 - t1

predicts=pw.cosine_similarity(feat, feat2)

t2 = time.time()

print predicts,t2 - t1
”’

原创粉丝点击