Keras a pre-trained model with multiple networks that can be easily used.
Installation and use main references official tutorial: https://keras.io/zh/applications/https://keras-cn.readthedocs.io/en/latest/other/application/
An example of using RESNET50 for ImageNet classification is given on the official website.
fromKeras.applications.resnet50ImportResNet50 fromKeras.preprocessingImportImage fromKeras.applications.resnet50ImportPreprocess_input, Decode_predictionsImportNumPy as Npmodel= ResNet50 (weights='imagenet') Img_path='elephant.jpg'img= Image.load_img (Img_path, target_size= (224, 224)) x=Image.img_to_array (img) x= Np.expand_dims (x, axis=0) x=preprocess_input (x) preds=model.predict (x)#decode the results into a list of tuples (class, description, probability)#(one such list for each sample in the batch)Print('predicted:', Decode_predictions (Preds, top=3) [0])#predicted: [(U ' n02504013 ', U ' indian_elephant ', 0.82658225), (U ' n01871265 ', U ' tusker ', 0.1122357), (U ' n02504458 ', u ' African_elephant ', 0.061040461)]
Then for other networks, you can refer to this code
First Vgg19
#Coding:utf-8 fromKeras.applications.vgg19ImportVGG19 fromKeras.preprocessingImportImage fromKeras.applications.vgg19ImportPreprocess_input fromKeras.modelsImportModelImportNumPy as Npbase_model= VGG19 (weights='imagenet', include_top=True) Model= Model (Inputs=base_model.input, Outputs=base_model.get_layer ('FC2'). Output) Img_path='.. /mdataset/img_test/p2.jpg'img= Image.load_img (Img_path, target_size= (224, 224)) x=Image.img_to_array (img) x= Np.expand_dims (x, axis=0) x=preprocess_input (x) FC2=model.predict (x)Print(Fc2.shape)#(1, 4096)
View Code
Then Mobilenet
#Coding:utf-8 fromKeras.applications.mobilenetImportmobilenet fromKeras.preprocessingImportImage fromKeras.applications.mobilenetImportpreprocess_input,decode_predictions fromKeras.modelsImportModelImportNumPy as NPImportTimemodel= Mobilenet (weights='imagenet', include_top=true,classes=1000) Start=time.time () Img_path='.. /mdataset/img_test/dog.jpg'img= Image.load_img (Img_path, target_size= (224, 224)) x=Image.img_to_array (img) x= Np.expand_dims (x, axis=0) x=preprocess_input (x) preds=model.predict (x)#decode the results into a list of tuples (class, description, probability)#(one such list for each sample in the batch)Print('predicted:', Decode_predictions (Preds, top=15) [0]) End=time.time ()Print('time:\n')PrintSTR (End-start)
View Code
Time statistics when the pseudo-statistical loading model time, probably takes less than 1 seconds, if the load model time to calculate in, about 3s
Keras using pre-trained models for image classification