Skip to content

Instantly share code, notes, and snippets.

@dersmon
Created November 12, 2015 10:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dersmon/8b701a41a3a1d6b45098 to your computer and use it in GitHub Desktop.
Save dersmon/8b701a41a3a1d6b45098 to your computer and use it in GitHub Desktop.
Using trained caffe model in python script, added value scaling and mean.
import sys
import caffe
import cv2
import Image
import numpy as np
from scipy.misc import imresize
caffe_root = "/home/simon/Workspaces/caffe/"
#MODEL_FILE = caffe_root + 'models/placesCNN/places205CNN_deploy.prototxt'
#PRETRAINED = caffe_root + 'models/placesCNN/places205CNN_iter_300000.caffemodel'
MODEL_FILE = caffe_root + 'models/customAlex/deploy.prototxt'
PRETRAINED = caffe_root + 'models/customAlex/caffe_alexnet_train_iter_1500.caffemodel'
net = caffe.Net(MODEL_FILE, PRETRAINED, caffe.TEST)
caffe.set_mode_cpu()
blob = caffe.proto.caffe_pb2.BlobProto()
data = open(caffe_root + 'models/customAlex/mean_train.binaryproto' , 'rb' ).read()
blob.ParseFromString(data)
meanArray = np.array( caffe.io.blobproto_to_array(blob) ).transpose(3,2,1,0)
meanArray = meanArray[:,:,:,0]
img = caffe.io.load_image(caffe_root + 'examples/images/Thess-11516his_110178,03.jpg')
img = img - meanArray
img = imresize(img, [227, 227])
img = img.astype(np.uint8)
imageData = np.asarray([img.transpose(2, 1, 0)])
imageData = np.divide(imageData, 255.0)
# out = net.forward_all(data=np.asarray([img.transpose(2, 0, 1)]))
out = net.forward_all(data=imageData)
print("Predicted class is #{}.".format(out['prob'][0].argmax()))
#imagenet_labels_filename = caffe_root + 'models/placesCNN/categoryIndex_places205.csv'
imagenet_labels_filename = caffe_root + 'models/customAlex/indexLabelMapping.txt'
labels = np.loadtxt(imagenet_labels_filename, str, delimiter='\s')
top_k = net.blobs['prob'].data[0].flatten().argsort()[-1: -6: -1]
print out['prob'][0]
print top_k
print labels[top_k]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment