[Python] How to correctly plot a bounding box on a 512x512 image using coordinates in Python?

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to plot a bounding box on a 512x512 image, but when I plot it, the box is not around the expected area of interest. I have extracted the top, left, bottom, and right coordinates from an XML file, and I am using these values to define the bounding box.

    Here are the coordinates I have for the bounding box:


    • Top: 459

      Left: 376

      Right: 388

      Bottom: 462

    The following points define the bounding box:


    • Top left: (376, 459)

      Top right: (388, 459)

      Bottom left: (376, 462)

      Bottom right: (388, 462)

    I am using matplotlib to display the image and plot the bounding box on it. However, plotting the bounding box does not seem to align with the area of interest.

    Here is the code I am using:

    import matplotlib.pyplot as plt

    # Coordinates for the bounding box
    top = 459
    left = 376
    right = 388
    bottom = 462

    # Define bounding box corners
    top_left = (left, top)
    top_right = (right, top)
    bottom_left = (left, bottom)
    bottom_right = (right, bottom)

    # Create the plot
    fig, ax = plt.subplots()

    # Set the title to the image name
    ax.set_title('Image with Bounding Box')

    # Display the image (assuming 'image' is your loaded 512x512 image)
    ax.imshow(image, cmap='gray')

    # Plot the bounding box by connecting the points
    ax.plot(
    [top_left[0], top_right[0], bottom_right[0], bottom_left[0], top_left[0]], # x-coordinates
    [top_left[1], top_right[1], bottom_right[1], bottom_left[1], top_left[1]], # y-coordinates
    markersize=5
    )

    # Set the limits based on image size
    ax.set_xlim(0, image.shape[1]) # Set x-axis limits to the image width
    ax.set_ylim(image.shape[0], 0) # Invert y-axis to match the image coordinate system

    # Show the plot
    plt.show()


    The resulting plot is Original Image

    Plot of Points on Image

    Problem: The bounding box does not align with the expected area of interest. I am plotting the coordinates correctly, but the box seems to be misplaced.

    What I’ve tried:

    I checked the coordinates and made sure the bounding box points were correct.

    I inverted the y-axis using ax.set_ylim(image.shape[0], 0) to match the image coordinate system.

    Questions

    What could be causing the bounding box to be misaligned?

    Are there any adjustments I need to make to the plotting code for the box to align properly with the image

    Continue reading...

Compartilhe esta Página