def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'caffe_feature_extractor.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'caffe_feature_extractor.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt in ("-i"):
inputfile = arg
elif opt in ("-o"):
outputfile = arg
print 'Reading images from "', inputfile
print 'Writing vectors to "', outputfile
# Setting this to CPU, but feel free to use GPU if you have CUDA installed
caffe.set_mode_gpu()
# Loading the Caffe model, setting preprocessing parameters
net = caffe.Classifier(model_prototxt, model_trained,
mean=np.load(mean_path).mean(1).mean(1),
channel_swap=(2,1,0),
raw_scale=255,
image_dims=(256, 256))
# Loading class labels
with open(imagenet_labels) as f:
labels = f.readlines()
# This prints information about the network layers (names and sizes)
# You can uncomment this, to have a look inside the network and choose which layer to print
#print [(k, v.data.shape) for k, v in net.blobs.items()]
#exit()
# Processing one image at a time, printint predictions and writing the vector to a file
with open(inputfile, 'r') as reader:
with open(outputfile, 'w') as writer:
writer.truncate()
for image_path in reader:
image_path = image_path.strip()
input_image = caffe.io.load_image(image_path)
prediction = net.predict([input_image], oversample=False)
print os.path.basename(image_path), ' : ' , labels[prediction[0].argmax()].strip() , ' (', prediction[0][prediction[0].argmax()] , ')'
np.savetxt(writer, net.blobs[layer_name].data[0].reshape(1,-1), fmt='%.8g')
评论列表
文章目录