Сервер Flask и клиент C # - PullRequest
0 голосов
/ 17 апреля 2019

Я создаю приложение, в котором есть колб-сервер для предсказания изображений и c # в качестве клиента через HTTP-запрос POST и для его обработки. Я проверил свой колб-сервер с клиентом python, он работает нормально, но когда я пытался связаться с c # клиент выдает ошибку типа BAD REQUEST 400.

Это мой код сервера

import flask
from flask import Flask,request
from flask_restful import Resource, Api
from keras.preprocessing.image import img_to_array
import numpy as np
import cv2
from keras.models import load_model
import imutils
from flask import jsonify
from PIL import Image
import os
import tensorflow as tf
from keras import backend as K
from werkzeug import secure_filename

app = Flask(__name__)

def preprocess(image):

    print("before",np.shape(image))
    img = imutils.resize(image, width=200)
    print("after",np.shape(img))
    final = np.expand_dims(img, axis=0)

    return final


@app.route('/predict',methods=["POST"])
def predict():

    model_file = 'cross_validation_v4_arc_red_4lyr.h5'
    model = load_model(model_file)
    file = flask.request.files['image']
    filename = secure_filename(file.filename) # save file 
    filepath = os.path.join(app.config['imgdir'], filename);
    file.save(filepath)
    image = cv2.imread(filepath)


    graph = tf.get_default_graph()

    with graph.as_default():
        data = {"success":False}

        final = preprocess(image)




        pred = model.predict(final)[0]
        print(pred)

        data["prediction"]= []

        result = pred.argmax()

        data["prediction"].append(str(result))

        data["success"] = True


    os.remove(filepath)

    return jsonify(data)


if __name__ == '__main__':

    K.clear_session()
    upload_folder = '/home/techvamp/Documents/Project/retina/Deployment'
    print("let the keras model load")
    app.config['imgdir'] = upload_folder
    app.run(debug=False, host='0.0.0.0',port=6500)

Это мой код клиента

using System;
using Tensorflow;
using System.Net.Http;
using System.IO;
using Json;
using System.Collections.Generic;


namespace scoring_rest_api
{

    class Program
    {
        static void Main(string[] args)
        {
             string uri = "http://localhost:6500/predict";
             String imageFile = "/home/techvamp/Documents/Project/retina/tf_serving/sample.png";

             FileStream F = new FileStream(imageFile, FileMode.Open,FileAccess.ReadWrite);

             HttpClient C = new HttpClient();
             HttpContent content = new StreamContent(F);

             //form.Add(content,"image");
             HttpResponseMessage message = null;
             try
             {
                 message = (C.PostAsync(uri, content)).Result;
             }
             catch(Exception ex)
             {
                 Console.WriteLine(ex);
             }

             var k = message.Content.ReadAsStringAsync().Result;
             Console.WriteLine(message);`
...