import pika
import base64
import json
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import StreamingResponse, HTMLResponse
from io import BytesIO
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
from detectron2.data import MetadataCatalog
def process(image, save_path):
im = read_base64(image)
outputs = predictor(im)
v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
# Save the processed image in the "save" folder
save_path = os.path.join("save", save_path)
cv2.imwrite(save_path, out.get_image()[:, :, ::-1])
return save_path
def on_request(ch, method, props, body):
try:
# Use a unique name for each processed image (e.g., using a counter)
image_counter = on_request.counter if hasattr(on_request, 'counter') else 1
save_path = f"processed_image_{image_counter}.jpg"
on_request.counter = image_counter + 1
result = process(body, save_path)
with open(result, "rb") as image_file:
image_str = base64.b64encode(image_file.read())
except Exception as e:
image_str = f'Error processing image: {str(e)}'
ch.basic_publish(exchange='',
routing_key=props.reply_to,
properties=pika.BasicProperties(correlation_id=props.correlation_id),
body=image_str)
ch.basic_ack(delivery_tag=method.delivery_tag)
save_folder = "save" # Adjust this to your desired save folder
@app.post("/process_image")
async def process_image(file: UploadFile = File(...)):
contents = await file.read()
try:
# Use a unique name for each processed image (e.g., using a counter)
process_image.counter = process_image.counter + 1 if hasattr(process_image, 'counter') else 1
save_path = os.path.join(save_folder, f"processed_image_{process_image.counter}.jpg")
Assistant
User
i want to upload image and do predection in this image and show it
Assistant
To upload an image, perform prediction using Detectron2, and display the result, you need to modify your FastAPI endpoint to process the image and return the modified image. Here's how to do it:
User
Backend QtAgg is interactive backend. Turning interactive mode on.
C:\Users\ayelg\anaconda3\Lib\site-packages\torch\functional.py:504: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at ..\aten\src\ATen\native\TensorShape.cpp:3527.)
return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined]
OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.
OMP: Hint This means that multiple copies of the OpenMP runtime have been linked into the program. That is dangerous, since it can degrade performance or cause incorrect results. The best thing to do is to ensure that only a single OpenMP runtime is linked into the process, e.g. by avoiding static linking of the OpenMP runtime in any library. As an unsafe, unsupported, undocumented workaround you can set the environment variable KMP_DUPLICATE_LIB_OK=TRUE to allow the program to continue to execute, but that may cause crashes or silently produce incorrect results. For more information, please see http://www.intel.com/software/products/support/.
Assistant
The warnings and errors you're seeing are related to different aspects of the libraries and environment you're using. Let's address them one by one:
User
{
"detail": "Error processing image: OpenCV(4.9.0) :-1: error: (-5:Bad argument) in function 'imwrite'\n> Overload resolution failed:\n> - Can't convert object to 'str' for 'filename'\n> - Can't convert object to 'str' for 'filename'\n"
}
Assistant
The error you're encountering is due to trying to use cv2.imwrite with a BytesIO buffer instead of a file path as its first argument. The cv2.imwrite function expects a file path as a string, not a buffer object. As mentioned previously, cv2.imwrite cannot be used to write directly into a buffer, so you have to use cv2.imencode to encode the image data to the appropriate format, and then you can write it into a BytesIO buffer.
User
why no segmentation in the image
Assistant
If you're not seeing segmentation in the output images, there could be several reasons:
User
example of prediction "import os
import cv2
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2 import model_zoo
from detectron2.utils.logger import setup_logger
from detectron2.data.datasets import register_coco_instances
from detectron2.data import MetadataCatalog
from detectron2.utils.visualizer import Visualizer
import datetime
You've provided a sample FastAPI app that has an endpoint for processing images using the Detectron2 library for instance segmentation in images. The app also sets up a RabbitMQ request handler for handling image processing asynchronously, although it seems to be an incomplete integration as the setup for the RabbitMQ connection is not included.
Here are some comments and suggestions to consider in your code:
In the read_base64 function, you're assuming that the base64_str is a byte-like object (split(b',')) which may fail if the input is a string. You might want to ensure that the input to this function is in the right format.
The process function returns a path to the saved image, which is not suitable for StreamingResponse. You should open and read the file contents into a buffer and then return this buffer instead.
In the process_image endpoint, you are trying to return StreamingResponse with result_buffer, but result_buffer returned by process is a file path, not the image buffer; you should change it to return the image buffer directly.
For the RabbitMQ handling on_request function, you need the initial setup for the RabbitMQ connection, queue declaration, and consuming setup, which is not included in the provided code.
It is important to have proper error handling to avoid server crashes. You've added some basic error handling in the read_base64 and process_image functions, which is good practice.
In the RabbitMQ callback function on_request, you're incrementing a counter to name the processed images uniquely. Note that if the server restarts, this counter will reset, potentially causing overwriting issues.
The provided HTML form content lacks action and method attributes with proper endpoint definition. You have to ensure that it points to the correct URL for file upload.
To address point 2 and 3, here's a corrected version of the end part of the process_image endpoint:
@app.post("/process_image")
async def process_image(file: UploadFile = File(...)):
contents = await file.read()
try:
# Use a unique name for each processed image (e.g., using a counter)
process_image.counter = process_image.counter + 1 if hasattr(process_image, 'counter') else 1
save_path = f"processed_image_{process_image.counter}.jpg"
result_path = process(contents, save_path)
# Read the processed image into memory
with open(result_path, 'rb') as result_file:
result_buffer = result_file.read()
# Respond with the image directly
return StreamingResponse(BytesIO(result_buffer), media_type="image/jpeg")
except Exception as e:
print(f"Error processing image: {str(e)}")
raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
Please, integrate RabbitMQ properly if you intend to use it and ensure your uploaded files and processed images are managed securely and efficiently (e.g., deleting temporary files), especially if dealing with sensitive data.
The /process_image endpoint will take an uploaded image file, run the prediction on it, save the modified image to a buffer, and return it as a response.
Remove or comment out the RabbitMQ related code (on_request function) if you are not using it.
Here's a modified version of your FastAPI code that does what you've asked:
@app.post("/process_image")
async def process_image(file: UploadFile = File(...)):
contents = await file.read()
try:
# Convert the uploaded file to a NumPy array
nparr = np.frombuffer(contents, np.uint8)
im = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
# Perform the prediction
outputs = predictor(im)
v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
# Save the processed image to a buffer
buffer = BytesIO()
result_image = out.get_image()[:, :, ::-1]
cv2.imwrite(buffer, result_image)
buffer.seek(0) # Go to the start of the buffer
# Respond with the image directly
return StreamingResponse(buffer, media_type="image/jpeg")
except Exception as e:
print(f"Error processing image: {str(e)}")
raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
# Keep the main endpoint and HTML form as is
With this endpoint, you can upload an image file via the HTML form provided by the main endpoint, and the /process_image endpoint will handle the uploaded file, perform the prediction, and return the resulting image directly in the browser.
Please note:
The cv2.imwrite function cannot write directly into a BytesIO buffer, so you might need to first write the image using cv2.imencode and then save the encoded image to the buffer.
The process_image endpoint defined above no longer saves the image on the server and instead streams the image directly back to the client.
Make sure your Detectron2 model is correctly configured for the image you are uploading. If the model expects images in a different format, some preprocessing might be required.
This should cover the full process from uploading the image to displaying the result, all within your FastAPI app. Make sure you test it thoroughly to catch any edge cases or errors that might occur with different image inputs.
Backend QtAgg is interactive backend. Turning interactive mode on.:
This is more of an informational message than an error or a warning. It's telling you that matplotlib has selected the 'QtAgg' backend, which is interactive. If you are not explicitly using matplotlib in your FastAPI app, this might be triggered by some other part of your environment. If it's undesired behavior, you can set the matplotlib backend to non-interactive before importing other modules:
import matplotlib
matplotlib.use('Agg')
torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument.:
This warning is letting you know about an upcoming change in PyTorch's meshgrid function, which will require an 'indexing' argument in future releases. It's generated internally by Detectron2 or another library using torch.meshgrid. Generally, you can ignore this warning as it is informational for future updates. The developers of Detectron2 will need to update their code to accommodate this change when the new PyTorch version is released.
The OpenMP (OMP) error is trickier. It indicates that you have multiple OpenMP runtimes linked into your program. Detectron2 (or PyTorch it's based on) and another library or application on your system link against different versions of the OpenMP library, leading to conflicts.
The suggested workaround (which should be used with caution) is to set the KMP_DUPLICATE_LIB_OK environment variable to TRUE. However, this workaround can potentially cause crashes or incorrect results as the warning suggests.
To apply the workaround environment variable, you could put the following line of code at the very beginning of your script before any imports:
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
Alternatively, you can set this variable directly in your operating system's environment before running your FastAPI app.
The better solution, however, is to ensure that your environment is clean and only one version of the OpenMP runtime is used. You might need to create a fresh Python environment or realign library versions to achieve compatibility.
Please handle the last error with care since silencing it does not solve the underlying problem; it only allows the program to run despite the issue's presence, which can be unsafe for production environments.
Here's how you update the /process_image endpoint to use cv2.imencode:
@app.post("/process_image")
async def process_image(file: UploadFile = File(...)):
contents = await file.read()
try:
# Convert the uploaded file to a NumPy array
nparr = np.frombuffer(contents, np.uint8)
im = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
# Perform the prediction
outputs = predictor(im)
v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
# Encode the processed image to JPEG format
ret, buffer = cv2.imencode('.jpg', out.get_image()[:, :, ::-1])
if not ret:
raise HTTPException(status_code=500, detail="Error encoding image.")
return StreamingResponse(BytesIO(buffer), media_type="image/jpeg")
except Exception as e:
print(f"Error processing image: {str(e)}")
raise HTTPException(status_code=500, detail=f"Error processing image: {e}")
This code performs the following:
After performing the prediction, it converts the processed image to a JPEG format using cv2.imencode.
The result of imencode is a tuple (ret, buffer), where ret is a boolean indicating success, and buffer is a buffer containing the encoded image.
If the encoding is successful (ret is True), you create a StreamingResponse to send the image buffer directly to the client.
If the encoding fails, we raise an HTTP exception with a 500 status code.
Incorrect Model Weights or Configuration: Make sure you have the correct model weights and configuration loaded. If these don't match the model architecture or are not properly loaded, it can result in poor or no segmentation.
Model Threshold: The detection confidence threshold cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 might be too high, which can cause the model to filter out detections it's not sufficiently confident about. You can try lowering this threshold to see if the model outputs any segmentation.
Input Image Format: Detectron2 models expect images in BGR format, as that's the format OpenCV uses. If you are feeding an image in RGB or another format without converting it, the model might not perform as expected.
Incorrect Image Preprocessing: When an image is distorted or not correctly preprocessed (e.g., resizing without maintaining aspect ratio), it can affect model detection ability.
Model's Ability: The model you have used might not be suited for the type of objects in your image, or it didn't learn to detect the objects you're trying to segment during its training.
Visualizer Issues: There could be an issue with the Visualizer displaying the output.
To diagnose the issue, you can add some logging to check if the model is detecting any instances, and what the scores are:
If you find that instances are being detected but not displayed, there might be an issue with the visualization step. Check the usage of the Visualizer and ensure it’s being used correctly:
v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
Make sure the im used in Visualizer(im[:, :, ::-1], ...) is correct and you're correctly handling the conversion from BGR to RGB if necessary (as Detectron2 expects RGB images for visualization).
If you're still having trouble, you might want to verify the model's performance using a different image or using the Detectron2's own scripts/tools to ensure that the model works as expected outside of your FastAPI application. This can help you pinpoint whether the issue is with the FastAPI integration or with the model itself.
The provided Python code defines a Predictor class with methods for running object detection and instance segmentation using a Detectron2 model. The code assumes you have a custom COCO-format dataset for "leaf" object detection and the corresponding JSON file and images located in the "PumpkinLeaf/" directory. It also assumes you have a pre-trained model saved as "model_final.pth".
Explanation of the Predictor class methods:
__init__: Initializes the Predictor class by setting up the Detectron2 configuration, registering the "leaf" dataset, and creating the prediction model using DefaultPredictor.
predict: Takes an image as input, runs the prediction using the predictor, and uses a Visualizer to draw the instance predictions on the image. The modified image is saved into the _img attribute.
processImage: Crops detected instances from the original image and saves them as separate files. It expands the detected boxes by 5 pixels on each side and saves the cropped images in the specified directory, with unique filenames based on the current timestamp.
Here's a streamlined example of how you could use the above class to run predictions on an uploaded image in FastAPI:
from fastapi import FastAPI, File, UploadFile
from starlette.responses import StreamingResponse
from io import BytesIO
import numpy as np
app = FastAPI()
predictor_instance = Predictor() # Initialize the predictor instance
@app.post("/process_image")
async def process_image_endpoint(file: UploadFile = File(...)):
contents = await file.read() # Read the contents of the uploaded file
nparr = np.frombuffer(contents, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) # Decode the image
predictor_instance.predict(img) # Run detection and visualization
visualized_img = predictor_instance.img # Get the visualized image
# Convert the visualized image to a JPEG format and return as a streaming response
ret, buffer = cv2.imencode('.jpg', visualized_img)
if not ret:
raise HTTPException(status_code=500, detail="Error encoding image.")
return StreamingResponse(BytesIO(buffer.tobytes()), media_type="image/jpeg")
# Other FastAPI code...
Remember to ensure that you have the dataset and model files set up correctly, and that the model is appropriate for the type of images you plan to use. If you're not seeing expected segmentation results, you need to check whether the dataset, model files, model weights, and configuration match the model you want to use. Further debugging would involve checking the scores, predictions, and the visualizer settings.