After learning from the previous two posts, we have trained a Caffemodel model and generated a deploy.prototxt file, and now we use these two files to classify and predict a new image.
We randomly look for an image from the test set in the Mnist dataset for experimentation.
#Coding=utf-8ImportCaffeImportNumPy as Nproot='/home/xxx/' #root directoryDeploy=root +'Mnist/deploy.prototxt' #Deploy fileCaffe_model=root +'Mnist/lenet_iter_9380.caffemodel' #well-trained Caffemodelimg=root+'Mnist/test/5/00008.png' #randomly looking for a picture to be measuredLabels_filename = root +'Mnist/test/labels.txt' #category name file, converting a numeric label back to the category nameNet= Caffe.net (Net_file,caffe_model,caffe. TEST)#load model and network#Picture preprocessing settingsTransformer = Caffe.io.Transformer ({'Data': net.blobs['Data'].data.shape})#set the shape format of the picture (1,3,28,28)Transformer.set_transpose ('Data', (2,0,1))#change the order of dimensions from the original picture (28,28,3) to (3,28,28)#Transformer.set_mean (' Data ', Np.load (mean_file). Mean (1). Mean (1)) #减去均值, there is no mean reduction in the previous training model .Transformer.set_raw_scale ('Data', 255)#Zoom to "0,255"Transformer.set_channel_swap ('Data', (2,1,0))#swap channels To change the image from RGB to BGRim=caffe.io.load_image (IMG)#Loading Picturesnet.blobs['Data'].data[...] = transformer.preprocess ('Data', IM)#perform the picture preprocessing action set above and load the picture into the blob#Perform testsout =Net.forward () labels= Np.loadtxt (Labels_filename, str, delimiter='\ t')#read the category name fileprob= net.blobs['Softmax1'].data[0].flatten ()#Remove the probability value of the last layer (Softmax) belonging to a category and printPrintProborder=prob.argsort () [0]#sort the probability value and take out the number of the maximum valuePrint 'The class is:', Labels[order]#convert the ordinal to the corresponding category name and print
Final output of the class Is:5
Sorted correctly.
If you are predicting multiple images, you can write the above file as a function and then cycle through the predictions.
Caffe Python Interface Learning (6): Use a well-trained model (Caffemodel) to classify new images