[关闭]
@hanxiaoyang 2016-10-10T05:08:45.000000Z 字数 1005 阅读 2571

caffe python 图像识别

未分类


example code by @寒小阳

  1. #example code by @Hanxiaoyang
  2. import numpy as np
  3. import sys
  4. import matplotlib.pyplot as plt
  5. # 这一步一定要保证,从caffe路径import
  6. caffe_root = '../' # 你的caffe编译文件夹路径
  7. sys.path.insert(0, caffe_root + 'python')
  8. import caffe
  9. # 我们如果已经训练好模型了,只是想做个图像识别的demo
  10. # 模型网络结构
  11. MODEL_FILE = '../models/bvlc_reference_caffenet/deploy.prototxt'
  12. # 预训练好的模型
  13. PRETRAINED = '../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'
  14. # 要识别的图像文件
  15. IMAGE_FILE = 'images/dog.jpg'
  16. # 选择使用cpu还是gpu
  17. caffe.set_mode_cpu()
  18. #使用gpu
  19. #caffe.set_device(0)
  20. #caffe.set_mode_gpu()
  21. # 用网络结构定义文件,预训练模型,训练集均值文件初始化分类器
  22. net = caffe.Classifier(MODEL_FILE, PRETRAINED,
  23. mean=np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1),
  24. channel_swap=(2,1,0),
  25. raw_scale=255,
  26. image_dims=(256, 256))
  27. # 载入待预测图片
  28. input_image = caffe.io.load_image(IMAGE_FILE)
  29. # 展示一下图片
  30. plt.imshow(input_image)
  31. # predict阶段,其实就是做前向运算,softmax输出概率
  32. prediction = net.predict([input_image])
  33. print 'prediction shape:', prediction[0].shape
  34. plt.plot(prediction[0])
  35. print 'predicted class:', prediction[0].argmax()
  36. plt.show()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注