The current version of OpenCV objective detection with FastAPI is temporary.

Posted by


In this tutorial, we will combine the power of OpenCV for object detection with FastAPI for building a RESTful API. We will use OpenCV to detect objects in an image and then create an endpoint in FastAPI to serve this functionality.

For this tutorial, make sure you have Python installed on your system along with the following libraries:

  • OpenCV (cv2)
  • FastAPI
  • Uvicorn

You can install these libraries using pip:

pip install opencv-python fastapi uvicorn

Now, let’s start by creating a FastAPI app that will handle our object detection endpoint. Create a new Python file (e.g., app.py) and add the following code:

from fastapi import FastAPI, UploadFile, File
import cv2

app = FastAPI()

@app.post("/detect_object/")
async def detect_object(file: UploadFile = File(...)):
    image = await file.read()
    nparr = np.fromstring(image, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

    # Perform object detection using OpenCV

    return {"result": "Object detected!"}

In this code, we have defined a FastAPI endpoint /detect_object/ that accepts an uploaded image file. The uploaded image is read and decoded using OpenCV. Now, we will add the object detection logic using OpenCV before returning a response.

Next, let’s add the object detection logic using OpenCV to our endpoint. You can use any pre-trained model for object detection, such as YOLO or SSD. For simplicity, we will use the Haar cascade classifier provided by OpenCV.

@app.post("/detect_object/")
async def detect_object(file: UploadFile = File(...)):
    image = await file.read()
    nparr = np.fromstring(image, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

    # Load the pre-trained Haar cascade classifier for detecting faces
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)

    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)

    ret, jpeg = cv2.imencode('.jpg', img)
    response_file = jpeg.tobytes()

    return StreamingResponse(io.BytesIO(response_file), media_type="image/jpeg")

In this code, we have loaded the pre-trained Haar cascade classifier for detecting faces and used it to detect faces in the uploaded image. We then drew rectangles around the detected faces before returning the image with the rectangles as a response.

To run the FastAPI app, use Uvicorn:

uvicorn app:app --reload

Now, you can test the object detection endpoint by sending a POST request with an image file to http://127.0.0.1:8000/detect_object/.

Congratulations! You have successfully built an object detection API using OpenCV and FastAPI. You can further enhance this functionality by using a more advanced object detection model and adding support for detecting multiple objects. Feel free to experiment and customize the code to suit your requirements.

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x