如何将以下Python脚本转换为C#?

时间:2019-02-10 02:56:02

标签: c# python tensorflow

我目前正在研究TF ML项目及其工作。我正在用C#编写客户端。我已经使用了更新的Python脚本进行测试,如下所示。

import requests
import json
from keras.preprocessing.image import img_to_array, array_to_img
from keras.preprocessing import image

flowers = ['c:/flower_photos/daisy/107592979_aaa9cdfe78_m.jpg', 'c:/flower_photos/daisy/134409839_71069a95d1_m.jpg', 'c:/flower_photos/daisy/144099102_bf63a41e4f_n.jpg','c:/flower_photos/daisy/154332674_453cea64f4.jpg']
for x in flowers:
    image1 = img_to_array(image.load_img(x, target_size=(128,128))) / 255
    payload = {
      "instances": [{'image': image1.tolist()},
    ]
    }
    print("sending request...")
    r = requests.post('http://localhost:8501/v1/models/squishbumps/versions/1:predict', json=payload)
    print(r.content)

我正在用C#实现它。在将图像转换为二进制和JSON格式方面,我遇到了困难。

我的C#例程如下

public string PostImageToServerAndClassify(string imagePath)
        {
            //https://stackoverflow.com/questions/9145667/how-to-post-json-to-a-server-using-c
            string result = null;
            string ModelName = cmbProjectNames.Text.Replace(" ", "");
            string status_url = String.Format("http://localhost:{0}/v1/models/{1}/versions/{2}:predict", txtPort.Text, ModelName, txtVersion.Text);
            string Base64Image = ImageToBase64String(imagePath);
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(status_url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = @"{"+ @"""instances""" + @":[{" + @"""image:""" +  Base64Image + @"}]}";

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }
            return result;
        }

图像到二进制的转换例程是

public string ImageToBase64String(string imagePath)
{
    //https://arcanecode.com/2007/03/21/encoding-strings-to-base64-in-c/
    System.Drawing.Image img = Image.FromFile(imagePath);
    MemoryStream ms = new MemoryStream();
    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    string returnValue = System.Convert.ToBase64String(ms.ToArray());
    return returnValue;
}

当前我遇到以下错误:

{
    "error": "JSON Parse error: Missing a name for object member. at offset: 1"
}

我确定我的json格式不正确。有人可以告诉我如何解决此问题吗?

如果我能看到在Python请求有效时通过嗅探端口来发送到Server的字符串是最好的。我可以检查的任何软件吗?

1 个答案:

答案 0 :(得分:0)

问题可能是引号内的冒号。试试:

"""image"":"而不是"""image:"""