hi can you make this professianl with good names and good function "import pika import…
- User
hi can you make this professianl with good names and good function "import pika import base64 import json from fastapi import FastAPI, File, UploadFile, HTTPException from fastapi.responses import StreamingResponse, HTMLResponse from detectron2.utils.logger import setup_logger import numpy as np import cv2 import os from detectron2 import model_zoo from detectron2.engine import DefaultPredictor from detectron2.config import get_cfg from detectron2.utils.visualizer import Visualizer, ColorMode from detectron2.data import MetadataCatalog import io from PIL import Image import uvicorn
import matplotlib matplotlib.use('Agg')
import os os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
app = FastAPI() setup_logger()
cfg = get_cfg() cfg.MODEL.DEVICE = "cpu"
cfg.merge_from_file("./detectron2_repo/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml") cfg.DATASETS.TRAIN = ("line_doc3",) cfg.DATASETS.TEST = () # no metrics implemented for this dataset cfg.DATALOADER.NUM_WORKERS = 2 cfg.SOLVER.IMS_PER_BATCH = 2 cfg.SOLVER.BASE_LR = 0.02 cfg.SOLVER.MAX_ITER = 10000 # 300 iterations seem good enough, but you can certainly train longer cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 128 # faster, and good enough for this toy dataset cfg.MODEL.ROI_HEADS.NUM_CLASSES = 3 # 3 classes (data, fig, hazelnut)
Use the pretrained model from the Detectron2 model zoo for initialization
cfg.MODEL.WEIGHTS = "detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl"
Save the trained model to the specified directory
cfg.OUTPUT_DIR = "./models/" cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model_letter.pth") cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set the testing threshold for this model
predictor = DefaultPredictor(cfg)
Ensure the "save" folder exists
if not os.path.exists("save"): os.makedirs("save")
def get_detectron2_predictions(image): outputs = predictor(image)
# Get predictions from the model instances = outputs["instances"].to("cpu") num_instances = len(instances) print(f"Number of instances detected: {num_instances}") # Draw bounding boxes on the image v = Visualizer(image[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8) # Ensure that there are instances to draw if num_instances > 0: out = v.draw_instance_predictions(instances) processed_image = out.get_image()[:, :, ::-1] print("Bounding boxes drawn.") else: processed_image = image print("No instances detected, returning the original image.") return processed_image@app.post('/process_image', response_class=HTMLResponse, status_code=200) async def process_image(file: UploadFile = File(...)): try: contents = await file.read() image = Image.open(io.BytesIO(contents)).convert("RGB") image_array = np.array(image)[:, :, ::-1].copy()
- Assistant
- User
i want to add the option to use model and visualise the detection mask
- Assistant
To add the functionality for visualizing detection masks along with bounding boxes and labels in your Detectron2 FastAPI application, you can modify the visualization part of the code that generates the output image. Below, changes are made to the
detect_objects_and_visualizefunction to overlay instance masks:# Other imports and code remain the same # Initialize the predictor predictor = load_model() # Define helper functions def detect_objects_and_visualize(image_array: np.ndarray) -> Any: """Detect objects in an image, visualize the results including masks""" outputs = predictor(image_array) # Ensure that there are instances to visualize num_instances = len(outputs["instances"]) if num_instances == 0: print("No instances detected, returning the original image.") return image_array print(f"Number of instances detected: {num_instances}") v = Visualizer(image_array[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8, instance_mode=ColorMode.IMAGE_BW) # We can use `ColorMode.IMAGE_BW` or `ColorMode.SEGMENTATION` to change the style of the masks out = v.draw_instance_predictions(outputs["instances"].to("cpu")) visualized_image = out.get_image()[:, :, ::-1] print("Masks and bounding boxes drawn.") return visualized_image # (Rest of the endpoint functions and image encoding functions remain the same) @app.post('/process_image', response_class=HTMLResponse, status_code=200) async def process_image(file: UploadFile = File(...)): # Code from previous example # (Rest of the code remains the same) if __name__ == "__main__": uvicorn.run(app, host="127.0.0.1", port=8000) - User
in the begining can you add function to shose model "cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, “model_letter.pth”)" i have two model in folder called "models"
- Assistant