SoFunction
Updated on 2024-12-19

caffe's python interface deploy generates caffemodel to categorize new images

caffe's python interface to generate deploy files

If you want to use the trained model to test a new image, you must have a file, which is actually similar to a file, except that the header and tail are not the same. the deploy file does not have the first data input layer, nor does it have the final Accuracy layer, but it does have an extra Softmax probability layer at the end.

Here we use the code approach to automatically generate this file, using mnist as an example.

# -*- coding: utf-8 -*-
from caffe import layers as L,params as P,to_proto
root='/home/xxx/'
deploy=root+'mnist/'    # File Save Path
def create_deploy():
    # Missing the first layer, the data layer #
    conv1=(bottom='data', kernel_size=5, stride=1,num_output=20, pad=0,weight_filler=dict(type='xavier'))
    pool1=(conv1, pool=, kernel_size=2, stride=2)
    conv2=(pool1, kernel_size=5, stride=1,num_output=50, pad=0,weight_filler=dict(type='xavier'))
    pool2=(conv2, pool=, kernel_size=2, stride=2)
    fc3=(pool2, num_output=500,weight_filler=dict(type='xavier'))
    relu3=(fc3, in_place=True)
    fc4 = (relu3, num_output=10,weight_filler=dict(type='xavier'))
    # There is no accuracy layer at the end, but there is a Softmax layer
    prob=(fc4)
    return to_proto(prob)
def write_deploy(): 
    with open(deploy, 'w') as f:
        ('name:"Lenet"\n')
        ('input:"data"\n')
        ('input_dim:1\n')
        ('input_dim:3\n')
        ('input_dim:28\n')
        ('input_dim:28\n')
        (str(create_deploy()))
if __name__ == '__main__':
    write_deploy()

After running the file, it will generate a file in the mnist directory, in the mnist directory.

This file is not recommended to use the code to generate, but rather troublesome. After you are familiar with it, you can make a copy of it and modify the corresponding places, which is more convenient.

The trained model caffemodel categorizes new images

After the previous learning, we have trained a caffemodel model and generated a file, now we will use these two files to classify a new image for prediction.

We find a random image from the test set of the mnist dataset and use it for our experiment.

#coding=utf-8
import caffe
import numpy as np
root='/home/xxx/'   # root directory
deploy=root + 'mnist/'    #deploy file
caffe_model=root + 'mnist/lenet_iter_9380.caffemodel'   # Trained caffemodel
img=root+'mnist/test/5/'    # A random picture found to be tested
labels_filename = root + 'mnist/test/'  # Category name file to convert numeric labels back to category names
net = (deploy,caffe_model,)   #Load the model and network
#Image Preprocessing Settings
transformer = ({'data': ['data'].})  # Set the shape format of the image (1,3,28,28).
transformer.set_transpose('data', (2,0,1))    # Change the order of the dimensions from the original image (28,28,3) to (3,28,28)
#transformer.set_mean('data', (mean_file).mean(1).mean(1)) #Subtract the mean; you didn't subtract the mean when you trained the model earlier, so you don't need to do it here.
transformer.set_raw_scale('data', 255)    # Scale to between [0, 255].
transformer.set_channel_swap('data', (2,1,0))   # Swap channels to change images from RGB to BGR
im=.load_image(img)                   #Load the picture
['data'].data[...] = ('data',im)      # Perform the image preprocessing operation set above and load the image into the blob
# Execute the test
out = ()
labels = (labels_filename, str, delimiter='\t')   #Read the category name file
prob= ['Softmax1'].data[0].flatten() # Take out the probability value that the last layer (Softmax) belongs to a category and print the
print prob
order=()[-1]  # Sort the probability values and take out the ordinal number where the maximum value is located
print 'the class is:',labels[order]   #Convert the serial number to the corresponding category name,print

The final output of the class is : 5

Categorized correctly.

If you are predicting multiple images, you can write this file above as a function and just do a loop prediction.

Above is the caffe python interface deploy generate caffemodel categorize new images in detail, more information about caffe python generate deploy image categorization please pay attention to my other related articles!