Rust 尝试从响应正文加载图像时不支持的图像格式

Rust 尝试从响应正文加载图像时不支持的图像格式,rust,image-uploading,Rust,Image Uploading,从开始,我尝试创建一个RESTAPI,它从请求主体中提取一个图像,以便对其进行分析。我使用以下cURL命令将图像上载到服务器: curl-i-X POST-F“image=@/Users/DanielBank/Desktop/grace_hopper.jpg”http://127.0.0.1:7878/ 尝试从内存加载图像时,出现不支持的图像格式错误: 线程'gotham-worker-0'在'Err'值:UnsupportedError(“不支持的图像格式”)'上调用'Result::unw

从开始,我尝试创建一个RESTAPI,它从请求主体中提取一个图像,以便对其进行分析。我使用以下cURL命令将图像上载到服务器:

curl-i-X POST-F“image=@/Users/DanielBank/Desktop/grace_hopper.jpg”http://127.0.0.1:7878/
尝试从内存加载图像时,出现不支持的图像格式错误:

线程'gotham-worker-0'在'Err'值:UnsupportedError(“不支持的图像格式”)'上调用'Result::unwrap()'时惊慌失措,src/libcore/Result.rs:999:5
/src/main.rs

extern crate futures;
extern crate gotham;
extern crate hyper;
extern crate mime;
extern crate url;

use futures::{future, Future, Stream};
use hyper::{Body, StatusCode};

use gotham::handler::{HandlerFuture, IntoHandlerError};
use gotham::helpers::http::response::create_response;
use gotham::router::builder::{build_simple_router, DefineSingleRoute, DrawRoutes};
use gotham::router::Router;
use gotham::state::{FromState, State};

use tract_core::ndarray;
use tract_core::prelude::*;

/// Extracts the image from a POST request and responds with a prediction tuple (probability, class)
fn prediction_handler(mut state: State) -> Box<HandlerFuture> {
  let f = Body::take_from(&mut state)
    .concat2()
    .then(|full_body| match full_body {
      Ok(valid_body) => {
        // load the model
        let mut model = tract_tensorflow::tensorflow()
          .model_for_path("mobilenet_v2_1.4_224_frozen.pb")
          .unwrap();

        // specify input type and shape
        model
          .set_input_fact(
            0,
            TensorFact::dt_shape(f32::datum_type(), tvec!(1, 224, 224, 3)),
          )
          .unwrap();

        // optimize the model and get an execution plan
        let model = model.into_optimized().unwrap();
        let plan = SimplePlan::new(&model).unwrap();
        let body_content = valid_body.into_bytes();

        // extract the image from the body as input
        let image = image::load_from_memory(body_content.as_ref())
          .unwrap()
          .to_rgb();
        let resized = image::imageops::resize(&image, 224, 224, ::image::FilterType::Triangle);
        let image: Tensor = ndarray::Array4::from_shape_fn((1, 224, 224, 3), |(_, y, x, c)| {
          resized[(x as _, y as _)][c] as f32 / 255.0
        })
        .into();

        // run the plan on the input
        let result = plan.run(tvec!(image)).unwrap();

        // find and display the max value with its index
        let best = result[0]
          .to_array_view::<f32>()
          .unwrap()
          .iter()
          .cloned()
          .zip(1..)
          .max_by(|a, b| a.0.partial_cmp(&b.0).unwrap());

        // respond with the prediction tuple
        let res = create_response(
          &state,
          StatusCode::OK,
          mime::TEXT_PLAIN,
          format!("{:?}", best.unwrap()),
        );
        future::ok((state, res))
      }
      Err(e) => future::err((state, e.into_handler_error())),
    });

  Box::new(f)
}

/// Create a `Router`
fn router() -> Router {
  build_simple_router(|route| {
    route.post("/").to(prediction_handler);
  })
}

/// Start a server and use a `Router` to dispatch requests
pub fn main() {
  let addr = "127.0.0.1:7878";
  println!("Listening for requests at http://{}", addr);
  gotham::start(addr, router())
}

问题是请求主体既有http头,也有图像数据。你需要根据语法来解析它

令人惊讶的是,我找不到现成的、像样的MIME多部分/表单数据解析器板条箱。下面的代码可以工作,但是它使用了非常粗糙的
regex
split,而不是正确的解析。此外,它省略了张量模型训练部分:

外部板条箱图像;
外部板条箱;
使用未来:{future,future,Stream};
使用gotham::handler::{HandlerFuture,IntoHandlerError};
使用gotham::helpers::http::response::create_response;
使用gotham::router::builder:{build_simple_router,DefineSingleRoute,DrawRoutes};
使用gotham::router::router;
使用gotham::state::{FromState,state};
使用hyper::{Body,StatusCode};
使用regex::bytes::regex;
fn预测处理程序(mut状态:状态)->框{
设f=Body::从(&mut状态)获取
.concat2()
.然后(|全身|匹配全身|{
正常(有效正文)=>{
让body_content=valid_body.into_bytes();
让re=Regex::new(r“\r\n\r\n”).unwrap();
let contents:Vec=re.split(body_content.as_ref()).collect();
让image=image::从_内存(内容[1])加载_。展开()到_rgb();
让res=create\u响应(
&国家,,
状态码::好的,
mime::纯文本,
格式!(“{:?}\r\n”,image.dimensions()),
);
未来::ok((状态,res))
}
Err(e)=>future::Err((state,e.into_handler_error()),
});
框::新(f)
}