Building a Keras + deep learning REST API (one of the trilogy)

Source: Internet
Author: User
Tags keras keras model

first, the basic environment$PIP Install flask gevent Requests Pillowwhere flask no need to explainThe gevent is used to automatically switch processes;Pillow is used for image processing under python;The requests is used for Python under request processing.
Second, the Core code interpretation# Import the necessary packages fromKeras.applicationsImportResNet50 fromKeras.preprocessing.imageImportImg_to_array fromKeras.applicationsImportImagenet_utils fromPILImportImageImportNumPy asNpImportFlaskImportIointroduce the required header files. The Keras of several classes of libraries is very universal;# Initialize our Flask application and the Keras modelApp = Flask. Flask (__name__) model =Noneinitialization of the class librarydef Load_model():# Load the pre-trained Keras model (here we are using a model# pre-trained on ImageNet and provided by Keras, but can# Substitute in your own networks just as easily) GlobalModel model = RESNET50 (Weights="Imagenet")Introducing Model models, if you want to introduce your own model (CBIR), is introduced here. def Prepare_image(Image,Target):# If the image mode is not RGB, convert itifImage.mode! ="RGB": Image = Image.convert ("RGB")
# Resize the input image and preprocess itImage = Image.resize (target) image = Img_to_array (image) image = Np.expand_dims (image,Axis=0) image = Imagenet_utils.preprocess_input (image)
# Return the processed imagereturnImageimage preprocessing, used here is Keras+pil, and the comparison between OpenCV, need to have time to do. @app. Route("/predict",Methods=["POST"])def predict():# Initialize the data dictionary that would be is returned from the# Viewdata = {"Success":False}
# Ensure an image is properly uploaded to our endpointifFlask.request.method = ="POST":ifFlask.request.files.get ("Image"):# Read the image in PIL formatImage = Flask.request.files["Image"].read () image = Image.open (io. Bytesio (image))
# Preprocess The image and prepare it for classificationImage = Prepare_image (image,Target=(224,224))
# classify the input image and then initialize the list# of predictions to return to the clientPreds = model.predict (image) results = imagenet_utils.decode_predictions (preds) data["Predictions"] = []
# Loop over the results and add them to the list of# returned predictions for(Imagenetid, label, prob)inchresults[0]: R = {"Label": Label,"Probability":float(Prob)} data["Predictions"].append (R)
# indicate that's the request was a successdata["Success"] =True
# Return the data dictionary as a JSON responsereturnFlask.jsonify (data)Although it is a core part, it is very easy to be reused. is the process of reading the data and then processing it.     # If This is the main thread of execution first load the model and# then start the serverif __name__=="__main__":Print(("* Loading Keras model and Flask starting server ...""Please wait until server has fully started")) Load_model () App.run ()
is less than the main process. Missing is not operational. third, the operation effectuse VPS to get results faster, at least you don't need to download resnet*.h5, a link is not too good for large objects.

the effect of flask operation, using curl for processing


Judging from the results, Curch ranked 2nd and identified the image as a bell tower or a monastery, a castle, a palace, there seems to be nothing wrong with it. Iv. Reflections on the summary
It is true that only a few lines of code have been passed to achieve the core issue of flask deployment. But just running this simple process, the machine has issued a huge amount of heat, on the other hand, the whole structure is what, but also need to further study clearly.




From for notes (Wiz)

Building a Keras + deep learning REST API (one of the trilogy)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.