Building a Keras + deep learning REST API(三部曲之一)

來源:互聯網
上載者:User

標籤:ssi   art   rop   post   www.   分享   __name__   convert   curl   

一、基本環境$ pip install flask gevent requests pillow其中 flask不需要解釋gevent 是用於自動切換進程的;pillow 是用來進行python下的影像處理的;requests 是用來進行python下request處理的。
二、核心代碼解釋# import the necessary packagesfrom keras.applications import ResNet50from keras.preprocessing.image import img_to_arrayfrom keras.applications import imagenet_utilsfrom PIL import Imageimport numpy as npimport flaskimport io引入所需的標頭檔。其中注意keras的幾個類庫是很有通用性的;# initialize our Flask application and the Keras modelapp = flask.Flask(__name__)model = None類庫的初始化def load_model():    # load the pre-trained Keras model (here we are using a model    # pre-trained on ImageNet and provided by Keras, but you can    # substitute in your own networks just as easily)    global model    model = ResNet50(weights="imagenet")引入model模型,如果想引入自己的模型(CBIR)的話,就在這裡引入。def prepare_image(image, target):    # if the image mode is not RGB, convert it    if image.mode != "RGB":        image = image.convert("RGB")
    # resize the input image and preprocess it    image = image.resize(target)    image = img_to_array(image)    image = np.expand_dims(image, axis=0)    image = imagenet_utils.preprocess_input(image)
    # return the processed image    return imageimage的預先處理,這裡使用的是keras+PIL,和opencv之間的比較,需要有時間來做。@app.route("/predict", methods=["POST"])def predict():    # initialize the data dictionary that will be returned from the    # view    data = {"success": False}
    # ensure an image was properly uploaded to our endpoint    if flask.request.method == "POST":        if flask.request.files.get("image"):            # read the image in PIL format            image = flask.request.files["image"].read()            image = Image.open(io.BytesIO(image))
            # preprocess the image and prepare it for classification            image = prepare_image(image, target=(224, 224))
            # classify the input image and then initialize the list            # of predictions to return to the client            preds = 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) in results[0]:                r = {"label": label, "probability": float(prob)}                data["predictions"].append(r)
            # indicate that the request was a success            data["success"] = True
    # return the data dictionary as a JSON response    return flask.jsonify(data)雖然是核心部分,但是其實非常容易被複用。就是讀取資料,然後進行處理的過程。    # 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()
比不可少的main過程。缺少不可運行。三、運行效果使用VPS能夠更快地得到效果,至少你不需要下載resnet*.h5,一個鏈路不是太好的大物件。

flask的運行效果,使用curl進行處理的效果


從結果上來看,curch排在了第2,而將這張圖片識別為鐘樓或者修道院、城堡,宮殿,似乎也沒有什麼不妥。四、小結反思
真的僅僅是通過了幾行代碼,就實現了flask部署的核心問題。不過光是跑這個簡單的過程,機器就已經發出巨大的熱量了;另一方面,整個的結構是什麼,也需要進一步去研究清楚才對。




來自為知筆記(Wiz)

Building a Keras + deep learning REST API(三部曲之一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.