美文网首页
Caffe(二)使用Python运用caffemodel进行mn

Caffe(二)使用Python运用caffemodel进行mn

作者: NoneLand | 来源:发表于2017-02-20 23:44 被阅读952次

    Problem Solve

    caffe入门与实践-LeNet MNIST 教程
    使用draw_net.py出错

    出错截图
    出现以上截图,经百度之后原因为Ubuntu``protobuff的版本较高,导致出错,然而并没有找到解决办法。已找到解决办法

    但随即又出现'int object has no attribute '__values问题,百度Google易一通之后,依然无解。然后在Caffe GithubIssue模块中找到这个问题,原来是最新版本draw.py的Bug,下载caffe-rc4.zip替换之后成功解决问题

    转换mnist ubyte3到图像

    参考:使用转换mnist数据库保存为bmp图片

    代码如下

    # -*- coding:utf-8 -*-
    
    import struct
    import numpy as np
    import matplotlib.pyplot as plt
    # import Image
    from PIL import Image  # import Image seems not work. 
    #二进制的形式读入
    filename='train-images-idx3-ubyte'
    binfile=open(filename,'rb')
    buf=binfile.read()
    #大端法读入4个unsigned int32
    #struct用法参见网站 http://www.cnblogs.com/gala/archive/2011/09/22/2184801.html
    
    index=0
    magic,numImages,numRows,numColumns=struct.unpack_from('>IIII',buf,index)
    index+=struct.calcsize('>IIII')
    numImages = 200  # 200 images is enough!
    #将每张图片按照格式存储到对应位置
    for image in range(0,numImages):
        im=struct.unpack_from('>784B',buf,index)
        index+=struct.calcsize('>784B')
       #这里注意 Image对象的dtype是uint8,需要转换
        im=np.array(im,dtype='uint8')
        im=im.reshape(28,28)
       # fig=plt.figure()
       # plotwindow=fig.add_subplot(111)
       # plt.imshow(im,cmap='gray')
       # plt.show()
        im=Image.fromarray(im)
        im.save('train/train_%s.bmp'%image,'bmp')
    

    使用模型配合OpenCV进行预测

    参考:caffe入门与实践-LeNet MNIST 教程

    在参考的基础上,将模型用于连续预测多张图像,并配合OpenCV给出识别效果。经过修改后的代码如下:

    # -*- coding:utf-8 -*-
    # Modified by NoneLand
    
    # 作者:晓雷
    # 链接:https://zhuanlan.zhihu.com/p/24110318
    # 来源:知乎
    # 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    
    import sys
    import numpy as np
    import cv2
    
    caffe_root = '/home/noneland/Software/caffe-master/'
    # This place must use full-path instead of ~. Otherwise netfile can't be open.
    sys.path.insert(0, caffe_root + 'python')  # 把pycaffe所在路径添加到环境变量
    import caffe
    
    # 指定网络结构 与 lenet_train_test.prototxt不同
    MODEL_FILE = caffe_root + '/examples/mnist/lenet.prototxt'
    PRETRAINED = caffe_root + '/examples/mnist/lenet_iter_10000.caffemodel'
    net = caffe.Classifier(MODEL_FILE, PRETRAINED)
    caffe.set_mode_cpu()
    
    IMAGE_PATH = '/home/noneland/WorkSpace/mnist_opencv_union/train/'
    font = cv2.FONT_HERSHEY_SIMPLEX
    
    for i in range(0, 200):
        # input_image = caffe.io.load_image(IMAG‵E_PATH + 'train_{}.bmp'.format(i), color=False)
        # astype() is a method provided by numpy to convert numpy dtype.
        input_image = cv2.imread(IMAGE_PATH + 'train_{}.bmp'.format(i), cv2.IMREAD_GRAYSCALE).astype(np.float32)
        resized = cv2.resize(input_image, (280, 280), None, 0, 0, cv2.INTER_AREA)
        # resize Image to improve vision effect.
        input_image = input_image[:, :, np.newaxis] # input_image.shape is (28, 28, 1), with dtype float32
        # The previous two lines(exclude resized line) is the same as what caffe.io.load_iamge() do.
        # According to the source code, caffe load_image uses skiamge library to load image from disk.
    
        # for debug
        # print type(input_image), input_image.shape, input_image.dtype
        # print input_image
    
        prediction = net.predict([input_image], oversample=False)
        cv2.putText(resized, str(prediction[0].argmax()), (200, 280), font, 4, (255,), 2, cv2.LINE_AA)
        cv2.imshow("Prediction", resized)
        print 'predicted class:', prediction[0].argmax()
        keycode = cv2.waitKey(0) & 0xFF
        if keycode == 27:
            break
    

    识别效果如下:

    mnist prediction

    整体上来看,在网络模型的生成阶段(即net = caffe.Classifier(MODEL_FILE, PRETRAINED))执行比较缓慢(此句存在较多的输出语句,后期可以考虑抑制输出以提高性能),后边的前向预测可以达到很高的实时性(这还是在CPU模式下,利用妙算的GPU性能或许可以进一步提高性能,降低延迟)。但是LeNet网络模型较小,不知道AlexNet表现如何。

    此外,在查看对应源代码之后,用OpenCV的接口重写了加载图像的方法。从代码里面可以看出,image对象与numpy关系紧密,单个像素点的操作直接可以用numpy的操作去做,一些需要联立像素点的操作才需要用OpenCV的函数(暂时这么理解)。不明白作者既然用了OpenCV库,为何不使用OpenCV的接口来加载图像,难道是为了提升IO性能,但是不同的库从磁盘中加载图像的差异又有多大呢?弄不明白。但是有一点很清楚,caffe的模块化程度确实很高,在自己写了加载图像之后仍然能正常的进行预测,只是在重写的过程中需要注意数组的尺寸(shape)和元素数据类型(dtype)一致,不然会出现问题。

    其他

    使用了Linux下面的byzanz工具配合xdotool(用于提取鼠标位置)制作动态图,效果很好。命令如下:

    noneland@NoneLand4DL:~$ xdotool getmouselocation
    noneland@NoneLand4DL:~$ sudo byzanz-record -d 30 --delay 5 -c -x 0 -y 0 -w 1280 -h 1080 lenet.gif

    `byzanz`使用截图

    另外,开源录屏软件OBS也很好用,很多直播就是用的基于OBS的软件。

    相关文章

      网友评论

          本文标题:Caffe(二)使用Python运用caffemodel进行mn

          本文链接:https://www.haomeiwen.com/subject/wpdewttx.html