当前位置:   article > 正文

【机器学习部署】Machine Learning Operations(MLOps) --1(利用fastapi部署yolov3模型)_mlops fastapi

mlops fastapi

上一章节已经实现了yolov3模型,接下来就要用fastapi来部署模型。代码如下

建立一个文件夹用来返回图片预测的结果 
  1. import os
  2. dir_name = "images_uploaded"
  3. if not os.path.exists(dir_name):
  4. os.mkdir(dir_name)

接下来实现部署模型代码

  1. import io
  2. import uvicorn
  3. import numpy as np
  4. import nest_asyncio
  5. from enum import Enum
  6. from fastapi import FastAPI, UploadFile, File, HTTPException
  7. from fastapi.responses import StreamingResponse
  8. import cv2
  9. import cvlib as cv
  10. from cvlib.object_detection import draw_bbox
  11. # Assign an instance of the FastAPI class to the variable "app".
  12. # You will interact with your api using this instance.
  13. app = FastAPI(title='Deploying a ML Model with FastAPI: 终于成功了!!!')
  14. # List available models using Enum for convenience. This is useful when the options are pre-defined.
  15. class Model(str, Enum):
  16. yolov3tiny = "yolov3-tiny"
  17. yolov3 = "yolov3"
  18. # By using @app.get("/") you are allowing the GET method to work for the / endpoint.
  19. @app.get("/")
  20. def home():
  21. return "Congratulations! Your API is working as expected. Now head over to http://localhost:8000/docs."
  22. # This endpoint handles all the logic necessary for the object detection to work.
  23. # It requires the desired model and the image in which to perform object detection.
  24. @app.post("/predict")
  25. def prediction(model: Model, file: UploadFile = File(...)):
  26. # 1. VALIDATE INPUT FILE
  27. filename = file.filename
  28. fileExtension = filename.split(".")[-1] in ("jpg", "jpeg", "png")
  29. if not fileExtension:
  30. raise HTTPException(status_code=415, detail="Unsupported file provided.")
  31. # 2. TRANSFORM RAW IMAGE INTO CV2 image
  32. # Read image as a stream of bytes
  33. image_stream = io.BytesIO(file.file.read())
  34. # Start the stream from the beginning (position zero)
  35. image_stream.seek(0)
  36. # Write the stream of bytes into a numpy array
  37. file_bytes = np.asarray(bytearray(image_stream.read()), dtype=np.uint8)
  38. # Decode the numpy array as an image
  39. image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
  40. # 3. RUN OBJECT DETECTION MODEL
  41. # Run object detection
  42. bbox, label, conf = cv.detect_common_objects(image, model=model)
  43. # Create image that includes bounding boxes and labels
  44. output_image = draw_bbox(image, bbox, label, conf)
  45. # Save it in a folder within the server
  46. cv2.imwrite(f'images_uploaded/{filename}', output_image)
  47. # 4. STREAM THE RESPONSE BACK TO THE CLIENT
  48. # Open the saved image for reading in binary mode
  49. file_image = open(f'images_uploaded/{filename}', mode="rb")
  50. # Return the image as a stream specifying media type
  51. return StreamingResponse(file_image, media_type="image/jpeg")
  52. # Allows the server to be run in this interactive environment
  53. nest_asyncio.apply()
  54. # Host depends on the setup you selected (docker or virtual env)
  55. host = "0.0.0.0" if os.getenv("DOCKER-SETUP") else "127.0.0.1"
  56. # Spin up the server!
  57. uvicorn.run(app, host=host, port=8000)
'
运行

运行后可以看到:

点击链接得到:

 

 再访问: http://localhost:8000/docs 如下图,并点击prediction

 再点击Try it out 

 

并且选择上传的图片,点击execute。 成功后在 images_uploaded文件夹可以得到结果。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号