前言
Github代码地址:https://github.com/HansRen1024/Object-Classification-of-Mapping-Features

后来做了一些改动,最新代码看Github吧,我就不在这里更新代码了。

Save_Feature_cam.py 通过摄像头拍摄,按空格键保存特征入库。

Contrast_Feature_cam.py 通过摄像头拍摄,按空格键比对特征,输出结果。

Save_image.py 保存大量图片用作特征库资源。每个类别保存三张图片。

Save_Feature_image.py 从上面收集的图片中保存特征入库。

Test_All.py 通过test.txt 文件中图片路径和类别索引进行测试。test.txt格式和训练caffe模型中生成LMDB文件的txt文件内容格式一致。[图片路径+空格+类别索引]

这个方法其实和人脸检测很像,只不过是用在了大众物品检测上面。优点是当你所要检测的物体数据集特别少或者不方便收集数据集的时候,效果很突出。同时也可以用作在线学习。具体原理也没什么难的,就是通过卷积神经网络提取特征,将某一层特征入库。重新再拍一张照片和所有库中特征求欧拉距离。不过选什么卷积网络,选哪一层特征要看情况而论。后来又完成了C++分别调用caffe和ncnn实现这个功能的代码。就不放出来了,感兴趣的话自己研究研究也不难。

下面代码关于调用caffe模块的内容不懂的话,可以看看我之前写的博文。包括怎样转换均值到.npy文件的代码都有。

http://blog.csdn.net/renhanchi/article/category/7066959

一、保存特征代码:

  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Mon Aug 28 13:09:05 2017
  5. @author: hans
  6. http://blog.csdn.net/renhanchi
  7. """
  8. import caffe
  9. import cv2
  10. import os
  11. import skimage
  12. import numpy as np
  13. import matplotlib.pyplot as plt
  14. prototxt='doc/deploy_squeezenet.prototxt'
  15. caffe_model='doc/squeezenet.caffemodel'
  16. mean_file='doc/mean_squeezenet.npy'
  17. caffe.set_mode_gpu()
  18. net = caffe.Net(prototxt,caffe_model,caffe.TEST)
  19. for name,feature in net.blobs.items(): #查看各层特征规模
  20. print name + '\t' + str(feature.data.shape)
  21. def show(data, padsize=1, padval=0):
  22. data -= data.min()
  23. data /= data.max()
  24. n = int(np.ceil(np.sqrt(data.shape[0])))
  25. padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
  26. data = np.pad(data, padding, mode='constant', constant_values=(padval, padval))
  27. data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
  28. data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
  29. plt.imshow(data)
  30. plt.axis('off')
  31. def saveFeat(image):
  32. global prob
  33. im = caffe.io.resize_image(image,(227,227,3))
  34. transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) #data blob 结构(n, k, h, w)
  35. transformer.set_transpose('data', (2, 0, 1)) #改变图片维度顺序,(h, w, k) -> (k, h, w)
  36. transformer.set_mean('data', np.load(mean_file).mean(1).mean(1))
  37. transformer.set_raw_scale('data', 255)
  38. net.blobs['data'].data[...] = transformer.preprocess('data', im)
  39. net.forward()
  40. # labels_filename='card/words_card.txt'
  41. # labels = np.loadtxt(labels_filename, str, delimiter='\t')
  42. # prob = net.blobs['prob'].data[0].flatten()
  43. # order = prob.argsort()[-1]
  44. # print 'class:', labels[order], 'accuracy: ', prob[order]
  45. conv1_data = net.blobs['conv10'].data[0] #提取特征
  46. conv1_data.tofile(claPath+'feat.bin')
  47. show(conv1_data)
  48. c = cv2.VideoCapture(0)
  49. while 1:
  50. ret, image = c.read()
  51. cv2.rectangle(image,(117,37),(522,442),(0,255,0),2)
  52. cv2.imshow("aaa", image)
  53. key = cv2.waitKey(10)
  54. if key == ord(' '):
  55. cla = str(raw_input("Please enter class name: "))
  56. claPath = os.path.join(r'features/%s/' %cla)
  57. if not os.path.exists(claPath):
  58. os.makedirs(claPath)
  59. else:
  60. print "This class has been saved before"
  61. os._exit(1)
  62. img = image[40:440, 120:520]
  63. img = skimage.img_as_float(image[40:440, 120:520]).astype(np.float32)
  64. saveFeat(img)
  65. elif key == 27:
  66. cv2.destroyAllWindows()
  67. break

二、对比特征代码:

  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Mon Aug 28 15:39:58 2017
  5. @author: hans
  6. http://blog.csdn.net/renhanchi
  7. """
  8. import caffe
  9. import cv2
  10. import os
  11. import skimage
  12. import numpy as np
  13. from math import sqrt
  14. dirpath = 'features/'
  15. prototxt='doc/deploy_squeezenet.prototxt'
  16. caffe_model='doc/squeezenet.caffemodel'
  17. mean_file='doc/mean_squeezenet.npy'
  18. caffe.set_mode_gpu()
  19. net = caffe.Net(prototxt,caffe_model,caffe.TEST)
  20. def contrastFeat(image):
  21. global similarity
  22. similarity = []
  23. cla = []
  24. im = caffe.io.resize_image(image,(227,227,3))
  25. transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) #data blob 结构(n, k, h, w)
  26. transformer.set_transpose('data', (2, 0, 1)) #改变图片维度顺序,(h, w, k) -> (k, h, w)
  27. transformer.set_mean('data', np.load(mean_file).mean(1).mean(1))
  28. transformer.set_raw_scale('data', 255)
  29. net.blobs['data'].data[...] = transformer.preprocess('data', im)
  30. net.forward()
  31. conv1_data = net.blobs['conv10'].data[0] #提取特征
  32. for dirname in os.listdir(dirpath):
  33. if os.path.isdir(r'%s%s/' %(dirpath, dirname)):
  34. claPath = os.path.join(r'%s%s/' %(dirpath, dirname))
  35. feat = np.fromfile(claPath+'feat.bin', dtype = np.float32)
  36. feat = feat.reshape(conv1_data.shape[0],conv1_data.shape[1],conv1_data.shape[2])
  37. dis = 0
  38. for n in range(feat.shape[0]):
  39. for h in range(feat.shape[1]):
  40. for w in range(feat.shape[2]):
  41. dis += pow(conv1_data[n,h,w]-feat[n,h,w],2)
  42. L2 = sqrt(dis)
  43. similarity.append(1/(1+L2))
  44. cla.append(dirname)
  45. similarity = np.array(similarity)
  46. print similarity
  47. order = similarity.argsort()[-1]
  48. print 'clss:', cla[order], 'prob:', similarity[order]
  49. c = cv2.VideoCapture(0)
  50. while 1:
  51. ret, image = c.read()
  52. cv2.rectangle(image,(117,37),(522,442),(0,255,0),2)
  53. cv2.imshow("aaa", image)
  54. key = cv2.waitKey(10)
  55. if key == ord(' '):
  56. img = image[40:440, 120:520]
  57. img = skimage.img_as_float(image[40:440, 120:520]).astype(np.float32)
  58. contrastFeat(img)
  59. elif key == 27:
  60. cv2.destroyAllWindows()
  61. break

ref
https://blog.csdn.net/renhanchi/article/details/77664687