本文整理汇总了Python中caffe.Classifier方法的典型用法代码示例。如果您正苦于以下问题:Python caffe.Classifier方法的具体用法?Python caffe.Classifier怎么用?Python caffe.Classifier使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类caffe
的用法示例。
在下文中一共展示了caffe.Classifier方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: classify
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def classify(images, config, weights):
""" Classifies our region proposals. """
print("Classifying: %d region images" % len(images))
assert(os.path.isfile(config) and os.path.isfile(weights))
# Caffe swaps RGB channels
channel_swap = [2, 1, 0]
# TODO: resizing on incoming config to make batching more efficient, predict
# loops over each image, slow
# Make classifier.
classifier = caffe.Classifier(config,
weights,
raw_scale=255,
channel_swap=channel_swap,
)
# Classify.
return classifier.predict(images, oversample=False)
示例2: predict
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def predict(sound_file, prototxt, model, output_path):
image_files = wav_to_images(sound_file, output_path)
caffe.set_mode_cpu()
net = caffe.Classifier(prototxt, model,
#image_dims=(224, 224)
#channel_swap=(2,1,0),
raw_scale=255 # convert 0..255 values into range 0..1
#caffe.TEST
)
input_images = np.array([caffe.io.load_image(image_file, color=False) for image_file in image_files["melfilter"]])
#input_images = np.swapaxes(input_images, 1, 3)
#prediction = net.forward_all(data=input_images)["prob"]
prediction = net.predict(input_images, False) # predict takes any number of images, and formats them for the Caffe net automatically
print prediction
print 'prediction shape:', prediction[0].shape
print 'predicted class:', prediction[0].argmax()
print image_files
return prediction
示例3: __init__
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def __init__(self, base_path, deploy_path=None, model_path=None,
patch_model="./tmp.prototxt", mean=(104.0, 116.0, 122.0),
channels=(2, 1, 0)):
# if the deploy path is None, set the default
if deploy_path is None:
deploy_path = base_path + "/deploy.prototxt"
# if the model path is None, set it to the default GoogleLeNet model
if model_path is None:
model_path = base_path + "/bvlc_googlenet.caffemodel"
# check to see if the model should be patched to compute gradients
if patch_model:
model = caffe.io.caffe_pb2.NetParameter()
text_format.Merge(open(deploy_path).read(), model)
model.force_backward = True
f = open(patch_model, "w")
f.write(str(model))
f.close()
# load the network and store the patched model path
self.net = caffe.Classifier(patch_model, model_path, mean=np.float32(mean),
channel_swap=channels)
self.patch_model = patch_model
示例4: create_classifier
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def create_classifier(pretrained_model):
"""Creates a model from saved caffemodel file and returns a classifier."""
# Creates model from saved .caffemodel.
# The following file are shipped inside caffe-doc Debian package
model_def = os.path.join("/", "usr", "share", "doc", "caffe-doc",
"models","bvlc_reference_caffenet",
"deploy.prototxt")
image_dims = [ 256, 256 ]
# The following file are shipped inside python3-caffe-cpu Debian package
mean = np.load(os.path.join('/', 'usr', 'lib', 'python3',
'dist-packages', 'caffe', 'imagenet',
'ilsvrc_2012_mean.npy'))
channel_swap = [2, 1, 0]
raw_scale = 255.0
caffe.set_mode_cpu()
classifier = caffe.Classifier(model_def, pretrained_model,
image_dims=image_dims, mean=mean,
raw_scale=raw_scale,
channel_swap=channel_swap)
return classifier
示例5: __load_net
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def __load_net(self):
# Load averaged image of ImageNet
img_mean_file = './examples/data/ilsvrc_2012_mean.npy'
img_mean = np.load(img_mean_file)
img_mean = np.float32([img_mean[0].mean(), img_mean[1].mean(), img_mean[2].mean()])
# Load CNN model
model_file = './examples/net/VGG_ILSVRC_19_layers/VGG_ILSVRC_19_layers.caffemodel'
prototxt_file = './examples/net/VGG_ILSVRC_19_layers/VGG_ILSVRC_19_layers.prototxt'
channel_swap = (2, 1, 0)
net = caffe.Classifier(prototxt_file, model_file,
mean=img_mean, channel_swap=channel_swap)
h, w = net.blobs['data'].data.shape[-2:]
net.blobs['data'].reshape(1, 3, h, w)
return net
示例6: _extract
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def _extract(self, inputs, layername):
# NOTE: we import the following codes from caffe.Classifier
shape = (
len(inputs), self.net.image_dims[0],
self.net.image_dims[1], inputs[0].shape[2])
input_ = np.zeros(shape, dtype=np.float32)
for ix, in_ in enumerate(inputs):
input_[ix] = resize_image(in_, self.net.image_dims)
# Take center crop.
center = np.array(self.net.image_dims) / 2.0
crop = np.tile(center, (1, 2))[0] + np.concatenate([
-self.net.crop_dims / 2.0,
self.net.crop_dims / 2.0
])
input_ = input_[:, crop[0]:crop[2], crop[1]:crop[3], :]
# Classify
caffe_in = np.zeros(
np.array(input_.shape)[[0, 3, 1, 2]], dtype=np.float32)
for ix, in_ in enumerate(input_):
caffe_in[ix] = \
self.net.transformer.preprocess(self.net.inputs[0], in_)
out = self.net.forward_all(
blobs=[layername], **{self.net.inputs[0]: caffe_in})[layername]
return out
示例7: make_i2v_with_caffe
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def make_i2v_with_caffe(net_path, param_path, tag_path=None, threshold_path=None):
mean = np.array([ 164.76139251, 167.47864617, 181.13838569])
net = Classifier(
net_path, param_path, mean=mean, channel_swap=(2, 1, 0))
kwargs = {}
if tag_path is not None:
tags = json.loads(open(tag_path, 'r').read())
assert(len(tags) == 1539)
kwargs['tags'] = tags
if threshold_path is not None:
fscore_threshold = np.load(threshold_path)['threshold']
kwargs['threshold'] = fscore_threshold
return CaffeI2V(net, **kwargs)
示例8: __init__
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def __init__(self, storage, model_file=settings.BERKELEY_MODEL_FILE, pretrained_file=settings.BERKELEY_CROP_PRET, image_mean=settings.ILSVRC_MEAN, make_net=True, xDim=4096):
super(CNN_Features_CAFFE_REFERENCE, self).__init__(storage)
self.STORAGE_SUB_NAME = 'cnn_feature_berkeley'
self.feature_layer = 'fc7'
self.feature_crop_index = 0
self.xDim = xDim
self.sub_folder = self.storage.get_sub_folder(
self.STORAGE_SUPER_NAME, self.STORAGE_SUB_NAME)
self.storage.ensure_dir(self.sub_folder)
self.model_file = model_file
self.pretrained_file = pretrained_file
self.image_mean = image_mean
self.full = False
if make_net:
self.net = caffe.Classifier(self.model_file,
self.pretrained_file,
mean=np.load(self.image_mean),
channel_swap=(2, 1, 0),
raw_scale=255, gpu=True)
示例9: __init__
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def __init__(self, model_def_file, pretrained_model_file, mean_file,
raw_scale, class_labels_file, bet_file, image_dim, gpu_mode):
logging.info('Loading net and associated files...')
if gpu_mode:
caffe.set_mode_gpu()
else:
caffe.set_mode_cpu()
self.net = caffe.Classifier(
model_def_file, pretrained_model_file,
image_dims=(image_dim, image_dim), raw_scale=raw_scale,
mean=np.load(mean_file).mean(1).mean(1), channel_swap=(2, 1, 0)
)
with open(class_labels_file) as f:
labels_df = pd.DataFrame([
{
'synset_id': l.strip().split(' ')[0],
'name': ' '.join(l.strip().split(' ')[1:]).split(',')[0]
}
for l in f.readlines()
])
self.labels = labels_df.sort('synset_id')['name'].values
self.bet = cPickle.load(open(bet_file))
# A bias to prefer children nodes in single-chain paths
# I am setting the value to 0.1 as a quick, simple model.
# We could use better psychological models here...
self.bet['infogain'] -= np.array(self.bet['preferences']) * 0.1
示例10: __init__
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def __init__(self, model, gpu_mode=False):
self.model = model
kwargs = {}
if self.model.get("image_dims"):
kwargs['image_dims'] = tuple(self.model.get("image_dims"))
if self.model.get("channel_swap"):
kwargs['channel_swap'] = tuple(self.model.get("channel_swap"))
if self.model.get("raw_scale"):
kwargs['raw_scale'] = float(self.model.get("raw_scale"))
if self.model.get("mean"):
kwargs['mean'] = numpy.array(self.model.get("mean"))
self.net = caffe.Classifier(
model.deploy_path(),
model.model_path(),
**kwargs
)
self.confidence_threshold = 0.1
if gpu_mode:
caffe.set_mode_gpu()
else:
caffe.set_mode_cpu()
self.labels = numpy.array(model.labels())
if self.model.bet_path():
self.bet = cPickle.load(open(self.model.bet_path()))
self.bet['words'] = map(lambda w: w.replace(' ', '_'), self.bet['words'])
else:
self.bet = None
self.net.forward()
示例11: list_layers
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def list_layers(network="bvlc_googlenet"):
# Load DNN model
NET_FN, PARAM_FN, CHANNEL_SWAP, CAFFE_MEAN = _select_network(network)
net = Classifier(
NET_FN, PARAM_FN, mean=CAFFE_MEAN, channel_swap=CHANNEL_SWAP)
net.blobs.keys()
示例12: deepdream_video
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def deepdream_video(
video, iter_n=10, octave_n=4, octave_scale=1.4,
end="inception_4c/output", clip=True, network="bvlc_googlenet",
frame_rate=24):
# Select, load DNN model
NET_FN, PARAM_FN, CHANNEL_SWAP, CAFFE_MEAN = _select_network(network)
net = Classifier(
NET_FN, PARAM_FN, mean=CAFFE_MEAN, channel_swap=CHANNEL_SWAP)
print("Extracting video...")
_extract_video(video)
output_dir = _output_video_dir(video)
images = listdir(output_dir)
print("Dreaming...")
for image in images:
image = "{}/{}".format(output_dir, image)
img = np.float32(img_open(image))
img = _deepdream(
net, img, iter_n=iter_n, octave_n=octave_n,
octave_scale=octave_scale, end=end, clip=clip)
img_fromarray(np.uint8(img)).save(image)
print("Creating dream video...")
_create_video(video, frame_rate)
print("Dream video created.")
示例13: __init__
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def __init__(self, model_def, pretrained_model, mean_file, label, image_dims = [256,256], channel_swap=[2,1,0], raw_scale=255.0, top_k=5):
super(CaffeEngine, self).__init__()
# Load model
caffe.set_mode_cpu()
self.classifier = caffe.Classifier(model_def, pretrained_model, image_dims=image_dims, mean=mean_file, raw_scale=raw_scale, channel_swap=channel_swap)
# Load labels
self.labels = [line.rstrip() for line in open(label)]
self.top_k = top_k
示例14: load_trained_net
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def load_trained_net(model_prototxt = None, model_weights = None):
assert (model_prototxt is None) == (model_weights is None), 'Specify both model_prototxt and model_weights or neither'
if model_prototxt is None:
load_dir = '/home/jyosinsk/results/140311_234854_afadfd3_priv_netbase_upgraded/'
model_prototxt = load_dir + 'deploy_1.prototxt'
model_weights = load_dir + 'caffe_imagenet_train_iter_450000'
print 'LOADER: loading net:'
print ' ', model_prototxt
print ' ', model_weights
net = caffe.Classifier(model_prototxt, model_weights)
#net.set_phase_test()
return net
示例15: get_bvlc_net
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Classifier [as 别名]
def get_bvlc_net(test_phase=True, gpu_mode=True):
net = caffe.Classifier(settings.DEFAULT_MODEL_FILE, settings.DEFAULT_PRETRAINED_FILE, mean=np.load(settings.ILSVRC_MEAN), channel_swap=(2, 1, 0), raw_scale=255)
if test_phase:
net.set_phase_test()
if gpu_mode:
net.set_mode_gpu()
return net