python调用caffe训练好的cifar10_quick_iter_4000.caffemodel模型检测单帧图片
python直接调用caffe训练好的模型,进行单帧图片检测,并显示检测结果。caffe自带的classify.py文件检测结果直接保存到了foo文件,不能直观显示,这里加入几行显示的代码,方便直接测试查看结果,运行OK,笔记mark。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182 1#!/usr/bin/env python
2"""
3classify.py is an out-of-the-box image classifer callable from the command line.
4
5By default it configures and runs the Caffe reference ImageNet model.
6"""
7import numpy as np
8import os
9import sys
10import argparse
11import glob
12import time
13
14import caffe
15
16
17def main(argv):
18 pycaffe_dir = os.path.dirname(__file__)
19
20 parser = argparse.ArgumentParser()
21 # Required arguments: input and output files.
22 parser.add_argument(
23 "input_file",
24 help="Input image, directory, or npy."
25 )
26 parser.add_argument(
27 "output_file",
28 help="Output npy filename."
29 )
30 # Optional arguments.
31 parser.add_argument(
32 "--model_def",
33 default=os.path.join(pycaffe_dir,
34 "../models/bvlc_reference_caffenet/deploy.prototxt"),
35 help="Model definition file."
36 )
37 parser.add_argument(
38 "--pretrained_model",
39 default=os.path.join(pycaffe_dir,
40 "../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel"),
41 help="Trained model weights file."
42 )
43 #新增显示部分
44 parser.add_argument(
45 "--labels_file",
46 default=os.path.join("../python/classify_words.txt"),
47 help="cifar result words file")
48 parser.add_argument(
49 "--force_grayscale",
50 action='store_true',
51 help="Convert RGB images down to single-channel grayscale versions," +
52 "usefull for single-channel networks like MNIST.")
53
54 parser.add_argument(
55 "--print_results",
56 action='store_true',
57 help="write output text to stdout rather than serializing to a file.")
58 #新增显示部分
59
60 parser.add_argument(
61 "--gpu",
62 action='store_true',
63 help="Switch for gpu computation."
64 )
65 parser.add_argument(
66 "--center_only",
67 action='store_true',
68 help="Switch for prediction from center crop alone instead of " +
69 "averaging predictions across crops (default)."
70 )
71 parser.add_argument(
72 "--images_dim",
73 default='256,256',
74 help="Canonical 'height,width' dimensions of input images."
75 )
76 parser.add_argument(
77 "--mean_file",
78 default=os.path.join(pycaffe_dir,
79 'caffe/imagenet/ilsvrc_2012_mean.npy'),
80 help="Data set image mean of [Channels x Height x Width] dimensions " +
81 "(numpy array). Set to '' for no mean subtraction."
82 )
83 parser.add_argument(
84 "--input_scale",
85 type=float,
86 help="Multiply input features by this scale to finish preprocessing."
87 )
88 parser.add_argument(
89 "--raw_scale",
90 type=float,
91 default=255.0,
92 help="Multiply raw input by this scale before preprocessing."
93 )
94 parser.add_argument(
95 "--channel_swap",
96 default='2,1,0',
97 help="Order to permute input channels. The default converts " +
98 "RGB -> BGR since BGR is the Caffe default by way of OpenCV."
99 )
100 parser.add_argument(
101 "--ext",
102 default='jpg',
103 help="Image file extension to take as input when a directory " +
104 "is given as the input file."
105 )
106 args = parser.parse_args()
107
108 image_dims = [int(s) for s in args.images_dim.split(',')]
109
110 mean, channel_swap = None, None
111 if args.mean_file:
112 mean = np.load(args.mean_file)
113 mean = mean.mean(1).mean(1)
114 if args.channel_swap:
115 channel_swap = [int(s) for s in args.channel_swap.split(',')]
116
117 if args.gpu:
118 caffe.set_mode_gpu()
119 print("GPU mode")
120 else:
121 caffe.set_mode_cpu()
122 print("CPU mode")
123
124 # Make classifier.
125 classifier = caffe.Classifier(args.model_def, args.pretrained_model,
126 image_dims=image_dims, mean=mean,
127 input_scale=args.input_scale, raw_scale=args.raw_scale,
128 channel_swap=channel_swap)
129
130 # Load numpy array (.npy), directory glob (*.jpg), or image file.
131 args.input_file = os.path.expanduser(args.input_file)
132 if args.input_file.endswith('npy'):
133 print("Loading file: %s" % args.input_file)
134 inputs = np.load(args.input_file)
135 elif os.path.isdir(args.input_file):
136 print("Loading folder: %s" % args.input_file)
137 inputs =[caffe.io.load_image(im_f)
138 for im_f in glob.glob(args.input_file + '/*.' + args.ext)]
139 else:
140 print("Loading file: %s" % args.input_file)
141 inputs = [caffe.io.load_image(args.input_file)]
142
143 print("Classifying %d inputs." % len(inputs))
144
145 # Classify.
146 start = time.time()
147 predictions = classifier.predict(inputs, not args.center_only)
148 print("Done in %.2f s." % (time.time() - start))
149 print("Predictions: %s" % predictions)
150
151 #新增显示部分
152 if args.print_results:
153 scores = predictions.flatten()
154 with open(args.labels_file) as f:
155 labels_df = pd.DataFrame([
156 {
157 'synset_id': l.strip().split(' ')[0],
158 'name': ' '.jion(l.strip().split(' ')[1:]).split(',')[0]
159 }
160 for l in f.readlines()])
161 labels = labels_df.sort('synset_id')['name'].values
162
163 indices = (-scores).argsort()[:5]
164 ps = labels[indices]
165
166 meta = [(p, '%.5f' % scores[i])
167 for i, p in zip(indices, ps)]
168 print meta
169 #新增显示部分
170
171 # Save
172 print("Saving results into %s" % args.output_file)
173 np.save(args.output_file, predictions)
174
175
176if __name__ == '__main__':
177 main(sys.argv)
178
179
180
181
182
调用cifar10_quick_iter_4000.caffemodel 模型进行检测
1
2
3
4
5
6
7 1cd ~/caffe/python
2
3ppython classify02.py --model_def ~/caffe/examples/cifar10/cifar10_quick.prototxt --pretrained_model ~/caffe/examples/cifar10/cifar10_quick_iter_4000.caffemodel --labels_file ~/caffe/data/cifar10/cifar10_words.txt --center_only ~/caffe/examples/images/fish-bike.jpg foo
4
5
6
7
运行结果如下:
直接用caffe默认用的ImageNet的模型进行检测
1
2
3
4
5
6 1cd ~/caffe/python
2
3python python/classify.py ~/caffe/examples/images/cat.jpg foo
4
5
6