本文整理汇总了Python中caffe.Net方法的典型用法代码示例。如果您正苦于以下问题:Python caffe.Net方法的具体用法?Python caffe.Net怎么用?Python caffe.Net使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类caffe
的用法示例。
在下文中一共展示了caffe.Net方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_caffe
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def load_caffe(model_desc, model_file):
"""
Load a caffe model. You must be able to ``import caffe`` to use this
function.
Args:
model_desc (str): path to caffe model description file (.prototxt).
model_file (str): path to caffe model parameter file (.caffemodel).
Returns:
dict: the parameters.
"""
with change_env('GLOG_minloglevel', '2'):
import caffe
caffe.set_mode_cpu()
net = caffe.Net(model_desc, model_file, caffe.TEST)
param_dict = CaffeLayerProcessor(net).process()
logger.info("Model loaded from caffe. Params: " +
", ".join(sorted(param_dict.keys())))
return param_dict
示例2: __init__
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def __init__(self, Xd=256):
print('ColorizeImageCaffe instantiated')
ColorizeImageBase.__init__(self, Xd)
self.l_norm = 1.
self.ab_norm = 1.
self.l_mean = 50.
self.ab_mean = 0.
self.mask_mult = 110.
self.pred_ab_layer = 'pred_ab' # predicted ab layer
# Load grid properties
self.pts_in_hull_path = './data/color_bins/pts_in_hull.npy'
self.pts_in_hull = np.load(self.pts_in_hull_path) # 313x2, in-gamut
# ***** Net preparation *****
示例3: prep_net
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def prep_net(self, gpu_id, prototxt_path='', caffemodel_path=''):
import caffe
print('gpu_id = %d, net_path = %s, model_path = %s' % (gpu_id, prototxt_path, caffemodel_path))
if gpu_id == -1:
caffe.set_mode_cpu()
else:
caffe.set_device(gpu_id)
caffe.set_mode_gpu()
self.gpu_id = gpu_id
self.net = caffe.Net(prototxt_path, caffemodel_path, caffe.TEST)
self.net_set = True
# automatically set cluster centers
if len(self.net.params[self.pred_ab_layer][0].data[...].shape) == 4 and self.net.params[self.pred_ab_layer][0].data[...].shape[1] == 313:
print('Setting ab cluster centers in layer: %s' % self.pred_ab_layer)
self.net.params[self.pred_ab_layer][0].data[:, :, 0, 0] = self.pts_in_hull.T
# automatically set upsampling kernel
for layer in self.net._layer_names:
if layer[-3:] == '_us':
print('Setting upsampling layer kernel: %s' % layer)
self.net.params[layer][0].data[:, 0, :, :] = np.array(((.25, .5, .25, 0), (.5, 1., .5, 0), (.25, .5, .25, 0), (0, 0, 0, 0)))[np.newaxis, :, :]
# ***** Call forward *****
示例4: __init__
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def __init__(self, model_weights, model_def, threshold=0.5, GPU_MODE=False):
if GPU_MODE:
caffe.set_device(0)
caffe.set_mode_gpu()
else:
caffe.set_mode_cpu()
self.net = caffe.Net(model_def, # defines the structure of the model
model_weights, # contains the trained weights
caffe.TEST) # use test mode (e.g., don't perform dropout)
self.threshold = threshold
self.transformer = caffe.io.Transformer({'data': self.net.blobs['data'].data.shape})
self.transformer.set_transpose('data', (2, 0, 1))
self.transformer.set_mean('data', np.array([127.0, 127.0, 127.0])) # mean pixel
self.transformer.set_raw_scale('data',
255) # the reference model operates on images in [0,255] range instead of [0,1]
self.transformer.set_channel_swap('data', (2, 1, 0)) # the reference model has channels in BGR order instead of RGB
image_resize = 300
self.net.blobs['data'].reshape(1, 3, image_resize, image_resize)
示例5: _initialize_caffe
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def _initialize_caffe(deploy_file, input_weight_file, training_mean_pickle, inference_width,
inference_height):
"""
Initializes Caffe to prepare to run some data through the model for inference.
"""
caffe.set_mode_gpu()
net = caffe.Net(deploy_file, input_weight_file, caffe.TEST)
# input preprocessing: 'data' is the name of the input blob == net.inputs[0]
transformer = caffe.io.Transformer({"data": net.blobs["data"].data.shape})
# PIL.Image loads the data with the channel last.
transformer.set_transpose("data", (2, 0, 1))
# Mean pixel.
transformer.set_mean("data", np.load(training_mean_pickle).mean(1).mean(1))
# The reference model operates on images in [0, 255] range instead of [0, 1].
transformer.set_raw_scale("data", 255)
# The reference model has channels in BGR order instead of RGB.
transformer.set_channel_swap("data", (2, 1, 0))
net.blobs["data"].reshape(1, 3, inference_height, inference_width)
return (net, transformer)
示例6: _load_pretrained_phocnet
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def _load_pretrained_phocnet(self, phocnet_bin_path, gpu_id, debug_mode, deploy_proto_path, phoc_size):
# create a deploy proto file
self.logger.info('Saving PHOCNet deploy proto file to %s...', deploy_proto_path)
mpg = ModelProtoGenerator(initialization='msra', use_cudnn_engine=gpu_id is not None)
proto = mpg.get_phocnet(word_image_lmdb_path=None, phoc_lmdb_path=None, phoc_size=phoc_size, generate_deploy=True)
with open(deploy_proto_path, 'w') as proto_file:
proto_file.write(str(proto))
# create the Caffe PHOCNet object
self.logger.info('Creating PHOCNet...')
if debug_mode:
phocnet = caffe.Net(deploy_proto_path, phocnet_bin_path, caffe.TEST)
else:
with Suppressor():
phocnet = caffe.Net(deploy_proto_path, phocnet_bin_path, caffe.TEST)
return phocnet
示例7: main
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def main():
args = parse_args()
sys.path.append(args.caffe_root)
import caffe
net = caffe.Net(args.caffe_proto, args.caffe_model, caffe.TEST)
print dir(net.layers[1].blobs[0])
# for i, x in enumerate(net._layer_names):
# print x, net.layers[i].type,
# if x in net.params:
# print net.params[x][0].shape
# print '\n'
model = bulid(net)
torch.save(model.state_dict(), args.caffe_proto.split('.')[0]+'.pth')
f = open(args.caffe_proto.split('.')[0]+'.py', 'w')
stdout = sys.stdout
sys.stdout = f
print 'model = ', model
sys.stdout = stdout
f.close()
示例8: net
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def net(weights=WEIGHTS):
"""
Get the caffe net that has been trained to segment facade features.
This initializes or re-initializes the global network with weights. There are certainly side-effects!
The weights default to a caffe model that is part of the same sourcecode repository as this file.
They can be changed by setting the I12_WEIGHTS environment variable, by passing a command line argument
to some programs, or programatically (of course).
:param weights: The weights to use for the net.
:return:
"""
global WEIGHTS
global _net
if _net is None or weights != WEIGHTS:
if weights is not None:
WEIGHTS = weights
_net = caffe.Net(LAYERS, WEIGHTS, caffe.TEST)
return _net
示例9: TestCaffe
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def TestCaffe(proto_path, model_path, inputs, LayerCheck, ModelInd):
net = caffe.Net(proto_path, model_path, caffe.TEST)
net.blobs['data'].data[...] = inputs
print('input blob:')
print(net.blobs['data'].data[...])
net.forward()
if LayerCheck == 'Softmax_1':
PrintLabel(net.blobs[LayerCheck].data[0].flatten())
else:
print(net.blobs[LayerCheck].data[0][...].flatten())
if (ModelInd == 17):
result_img = net.blobs[LayerCheck].data[0] * 255
result_img = result_img.astype(int)
result_img = np.transpose(result_img, (1, 2, 0))
result_img = result_img[..., ::-1]
cv2.imwrite("AnimeNet_result.png", result_img)
if (ModelInd == 91):
result_img = net.blobs[LayerCheck].data[0] * 255
result_img = result_img.astype(int)
result_img = np.transpose(result_img, (1, 2, 0))
result_img = result_img[..., ::-1]
cv2.imwrite("Upsample_result.png", result_img)
示例10: inference
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def inference(cls, architecture_name, architecture, path, image_path):
if cls.sanity_check(architecture_name):
import caffe
import numpy as np
net = caffe.Net(architecture[0], architecture[1], caffe.TEST)
func = TestKit.preprocess_func['caffe'][architecture_name]
img = func(image_path)
img = np.transpose(img, (2, 0, 1))
img = np.expand_dims(img, 0)
net.blobs['data'].data[...] = img
predict = np.squeeze(net.forward()[net._output_list[-1]][0])
predict = np.squeeze(predict)
return predict
else:
return None
示例11: read_caffemodel
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def read_caffemodel(prototxt_fname, caffemodel_fname):
"""Return a caffe_pb2.NetParameter object that defined in a binary
caffemodel file
"""
if use_caffe:
caffe.set_mode_cpu()
net = caffe.Net(prototxt_fname, caffemodel_fname, caffe.TEST)
layer_names = net._layer_names
layers = net.layers
return (layers, layer_names)
else:
proto = caffe_pb2.NetParameter()
with open(caffemodel_fname, 'rb') as f:
proto.ParseFromString(f.read())
return (get_layers(proto), None)
示例12: caffe_preprocess_and_compute
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def caffe_preprocess_and_compute(pimg, caffe_transformer=None, caffe_net=None,
output_layers=None):
"""
Run a Caffe network on an input image after preprocessing it to prepare
it for Caffe.
:param PIL.Image pimg:
PIL image to be input into Caffe.
:param caffe.Net caffe_net:
A Caffe network with which to process pimg afrer preprocessing.
:param list output_layers:
A list of the names of the layers from caffe_net whose outputs are to
to be returned. If this is None, the default outputs for the network
are returned.
:return:
Returns the requested outputs from the Caffe net.
"""
if caffe_net is not None:
# Grab the default output names if none were requested specifically.
if output_layers is None:
output_layers = caffe_net.outputs
img_data_rs = resize_image(pimg, sz=(256, 256))
image = caffe.io.load_image(StringIO(img_data_rs))
H, W, _ = image.shape
_, _, h, w = caffe_net.blobs['data'].data.shape
h_off = max((H - h) / 2, 0)
w_off = max((W - w) / 2, 0)
crop = image[h_off:h_off + h, w_off:w_off + w, :]
transformed_image = caffe_transformer.preprocess('data', crop)
transformed_image.shape = (1,) + transformed_image.shape
input_name = caffe_net.inputs[0]
all_outputs = caffe_net.forward_all(blobs=output_layers,
**{input_name: transformed_image})
outputs = all_outputs[output_layers[0]][0].astype(float)
return outputs
else:
return []
示例13: main
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def main(argv):
pycaffe_dir = os.path.dirname(__file__)
parser = argparse.ArgumentParser()
# Required arguments: input file.
parser.add_argument(
"input_file",
help="Path to the input image file"
)
# Optional arguments.
parser.add_argument(
"--model_def",
help="Model definition file."
)
parser.add_argument(
"--pretrained_model",
help="Trained model weights file."
)
args = parser.parse_args()
image_data = open(args.input_file).read()
# Pre-load caffe model.
nsfw_net = caffe.Net(args.model_def, # pylint: disable=invalid-name
args.pretrained_model, caffe.TEST)
# Load transformer
# Note that the parameters are hard-coded for best results
caffe_transformer = caffe.io.Transformer({'data': nsfw_net.blobs['data'].data.shape})
caffe_transformer.set_transpose('data', (2, 0, 1)) # move image channels to outermost
caffe_transformer.set_mean('data', np.array([104, 117, 123])) # subtract the dataset-mean value in each channel
caffe_transformer.set_raw_scale('data', 255) # rescale from [0, 1] to [0, 255]
caffe_transformer.set_channel_swap('data', (2, 1, 0)) # swap channels from RGB to BGR
# Classify.
scores = caffe_preprocess_and_compute(image_data, caffe_transformer=caffe_transformer, caffe_net=nsfw_net, output_layers=['prob'])
# Scores is the array containing SFW / NSFW image probabilities
# scores[1] indicates the NSFW probability
print "NSFW score: " , scores[1]
示例14: load_weigths_from_caffe
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def load_weigths_from_caffe(self, protofile, caffemodel):
caffe.set_mode_cpu()
net = caffe.Net(protofile, caffemodel, caffe.TEST)
for name, layer in self.models.items():
if isinstance(layer, nn.Conv2d):
caffe_weight = net.params[name][0].data
layer.weight.data = torch.from_numpy(caffe_weight)
if len(net.params[name]) > 1:
caffe_bias = net.params[name][1].data
layer.bias.data = torch.from_numpy(caffe_bias)
continue
if isinstance(layer, nn.BatchNorm2d):
caffe_means = net.params[name][0].data
caffe_var = net.params[name][1].data
layer.running_mean = torch.from_numpy(caffe_means)
layer.running_var = torch.from_numpy(caffe_var)
# find the scale layer
top_name_of_bn = self.layer_map_to_top[name][0]
scale_name = ''
for caffe_layer in self.net_info['layers']:
if caffe_layer['type'] == 'Scale' and caffe_layer['bottom'][0] == top_name_of_bn:
scale_name = caffe_layer['name']
break
if scale_name != '':
caffe_weight = net.params[scale_name][0].data
layer.weight.data = torch.from_numpy(caffe_weight)
if len(net.params[name]) > 1:
caffe_bias = net.params[scale_name][1].data
layer.bias.data = torch.from_numpy(caffe_bias)
示例15: main
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import Net [as 别名]
def main():
"""Extract and save network skeleton with the corresponding weights.
Raises:
ImportError: PyCaffe module is not found."""
args = get_arguments()
sys.path.append(args.pycaffe_path)
try:
import caffe
except ImportError:
raise
# Load net definition.
net = caffe.Net('./util/deploy.prototxt', args.caffemodel, caffe.TEST)
# Check the existence of output_dir.
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
# Net skeleton with parameters names and shapes.
# In TF, the filter shape is as follows: [ks, ks, input_channels, output_channels],
# while in Caffe it looks like this: [output_channels, input_channels, ks, ks].
net_skeleton = list()
for name, item in net.params.iteritems():
net_skeleton.append([name + '/w', item[0].data.shape[::-1]]) # See the explanataion on filter formats above.
net_skeleton.append([name + '/b', item[1].data.shape])
with open(os.path.join(args.output_dir, 'net_skeleton.ckpt'), 'wb') as f:
cPickle.dump(net_skeleton, f, protocol=cPickle.HIGHEST_PROTOCOL)
# Net weights.
net_weights = dict()
for name, item in net.params.iteritems():
net_weights[name + '/w'] = item[0].data.transpose(2, 3, 1, 0) # See the explanation on filter formats above.
net_weights[name + '/b'] = item[1].data
with open(os.path.join(args.output_dir,'net_weights.ckpt'), 'wb') as f:
cPickle.dump(net_weights, f, protocol=cPickle.HIGHEST_PROTOCOL)
del net, net_skeleton, net_weights