1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Draw onto image, then show and save result

Discussão em 'Python' iniciado por Stack, Setembro 15, 2025.

  1. Stack

    Stack Membro Participativo

    This is what I want to do:

    • Read in an image from disk (pngs in my case)
    • Draw some shapes into it, like rectangles, ...
    • Display the resulting image in my jupyter notebook and also save it back to file

    I'm currently using matplotlib for the drawing part. The issue: This process does not preserve resolution. The resulting png written to file is scaled by some random amount. As far as I understand, this is because matplotlib is using physical units and everything is dependent on screen size etc. That's a problem for me because I want to have pixel perfect drawing of the shapes and draw/save the image in the exact same resolution. I'm beginning to think that matplotlib might not be the right tool for what I want to do.

    Any advice? Below is the code I am currently using.

    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    import matplotlib.patches as patches

    # Read the image.
    image_path = 'input_image.png'
    output_image_path = 'output_image.png'
    image = mpimg.imread(image_path)

    # Create a figure.
    fig, ax = plt.subplots(1)
    ax.axis('off')

    # Create a rectangle patch and add it.
    rect = patches.Rectangle((100, 100), 20, 20, linewidth=1, edgecolor='r', facecolor='none')
    ax.add_patch(rect)
    ax.imshow(image)

    # Save result.
    plt.savefig(output_image_path, bbox_inches='tight', pad_inches=0)

    # Input image: (1200x800)
    # Output image: (496x330)

    Continue reading...

Compartilhe esta Página