#coding:utf-8
import sys
sys.path.insert(0,"/home/caffe/python")
import caffe
import cv2
import numpy as np
import time
import glob
from tqdm import tqdm
def person_top1():
deploy = './v0.prototxt'
caffe_model = './v0.caffemodel'
caffe.set_device(0)
caffe.set_mode_gpu()
net = caffe.Net(deploy,caffe_model,caffe.TEST) #
print("net load suceed")
print("==============================================>")
print("now extracting img feature, please wait a minutes ...")
img_feats = []
label = []
for path in tqdm(glob.glob("./test_img/*.png")):
# tensor preprocess
# print path
img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #bgr to rgb
img = cv2.resize(img,(128,256))
img = img.transpose(2, 0, 1) # hwc to chw
# img = (img-127.5)*0.0078125 #normalize
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
img = img / 255.0
# Normalization
for channel, _ in enumerate(img):
img[channel] -= mean[channel]
img[channel] /= std[channel]
net.blobs['data'].data[...] = img #nchw 数据输入,但是这里net.blobs['data'].data[...] ,输入chw
net.forward() #前向传输也有其他写法
feature = np.float64(net.blobs["batch_norm_blob54"].data[0])
img_feats.append(feature.flatten())
lab = path.split("/")[2].split("_")[0]
label.append(int(lab))
img_feats = np.array(img_feats).astype(np.float32) # \u6240\u6709\u56fe\u7247numpy,
g_feats = img_feats
t_feats = img_feats
g_feats = g_feats / np.sqrt(np.sum(g_feats ** 2, -1, keepdims=True))
t_feats = t_feats / np.sqrt(np.sum(t_feats ** 2, -1, keepdims=True))
# gallery_label=np.concatenate((test_feats30, test_feats40), axis=0) #\u62fc\u63a5
### \u7279\u5f81\u63d0\u53d6\u7ed3\u675f\uff0c\u8fdb\u884c \u6bd4\u5bf9\uff0c top
print("all img feature dimension", img_feats.shape)
correct10 = 0
correct1 = 0
for i, line in enumerate(t_feats):
line = np.tile(line, (len(g_feats), 1)) # 一个特征维度,重复 所有维度
dis = np.sum(g_feats * line, 1) # save index correspond index
sort_index = np.argsort(-dis, axis=0) #大小排序 没有- 小大排序
top100 = []
temp_label = []
# for j in range(101): #get sort index
for j in range(11): # get sort index
# top100.append(dis[sort_index[j]])
temp_label.append(label[sort_index[j]]) ##gallery label
if label[i] in temp_label[1:11]: # test_label is 1,because Remove its own
correct10 = correct10 + 1
if label[i] in temp_label[1:2]:
correct1 = correct1 + 1
print("=====================================================>")
print ("top1 : ", correct1 / float(len(t_feats)))
print ("top10 : ", correct10 / float(len(t_feats)))
## test
top1()
caffe 读取图片,测试
最新推荐文章于 2020-12-24 23:18:33 发布