Skip to content
The Chat Archive
gpt-4-0314· OpenAI WildChat-4.8M (AI2)

I have a person bounding box, i want to extract the countours of the person, a polygon,…

  1. User

    I have a person bounding box, i want to extract the countours of the person, a polygon, inside the bounding box using opencv

  2. Assistant

    To extract the contours of a person inside the bounding box using OpenCV, you can follow these steps:

    1. Perform image preprocessing like resizing, grayscaling, and Gaussian blurring.
    2. Apply edge detection using the canny function.
    3. Extract contours using the findContours function.
    4. Filter only the contour that matches the bounding box dimensions.
    5. Draw the detected contour using the drawContours function.

    Here's a code that demonstrates these steps:

    import cv2
    import numpy as np
    
    # Load the image and resize
    image = cv2.imread("person.jpg")
    image = cv2.resize(image, (600, 400))
    
    # Coordinates of the bounding box (x,y,width,height)
    bounding_box = (50, 50, 200, 300)
    
    # Preprocess image - convert to grayscale and blur
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    
    # Edge detection
    edges = cv2.Canny(blurred, 50, 150)
    
    # Find contours
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    # Filter the contour that matches the bounding box dimensions
    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)
        if x == bounding_box[0] and y == bounding_box[1] and w == bounding_box[2] and h == bounding_box[3]:
            cv2.drawContours(image, [contour], -1, (0, 255, 0), 3)
            break
    
    # Show original image and image with contour
    cv2.imshow("Image", image)
    cv2.imshow("Edges", edges)
    cv2.waitKey(0)
    

    This code assumes that a polygon contour around the person exists within the bounding box. Note that the accuracy of the contour detection heavily depends on the quality of edge detection, which in turn depends on how well the image is preprocessed. You may need to adjust the parameters of the canny function and other preprocessing steps based on your specific image.