Skip to content

[Bug]: bbox floating point size mismatch #21879

Closed as duplicate
Closed as duplicate

Description

@blatr

Bug summary

Hi! matplotlib treats incorrectly floating figsize.

Code for reproduction

import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np

dpi = 100
h = 1708
w = 2560
height_inches = float(h) / dpi
width_inches = float(w) / dpi
fig = plt.figure(figsize=(width_inches, height_inches), dpi=dpi)
plt.axes([0, 0, 1, 1])
plt.axis("off")

canvas = FigureCanvas(fig)
extent = (0, 2560, 1708, 0)
plt.imshow(np.zeros((2560, 1708,3)), extent=extent)
canvas.draw()
fig.clear()
plt.close(fig)

original_image = np.fromstring(canvas.tostring_rgb(), dtype="uint8").reshape(h, w, 3)

Actual outcome

ValueError: cannot reshape array of size 13109760 into shape (1708,2560,3)

Expected outcome

array of size (1708,2560,3)

Additional information

Problem appears from rounding error in variable "height_inches" which results in wrong argument in line.
At this line width is equal to 1707.9999999999998 and int(1707.9999999999998)=1707 but not 1708 as expected

Operating system

Ubuntu 18.04.5 LTS (Bionic Beaver)

Matplotlib Version

3.3.4

Matplotlib Backend

agg

Python version

3.7.10

Jupyter version

No response

Installation

conda

Activity

  1. tacaswell commented on Dec 7, 2021

    @tacaswell
    Member

    I can produce this with on ~main and a duplicate of #15363

    #8265 is a pass at moving to round rather than int, but it is now far out of date (and was failing tests due to the changes induced) and I suspect does not yet hit enough places (a number of the GUI frameworks just got stricter about ints vs floats so we now have more explicit casts than we used to).

  2. added this to the v3.6.0 milestone on Dec 7, 2021
  3. TangChiaHsin commented on Dec 12, 2021

    @TangChiaHsin

    Adding .1 can not solve this problem in macOS system.

    ValueError: cannot reshape array of size 1090560 into shape (427,640,4)
    

    The figure size will be changed into 4266404.

  4. modified the milestones: v3.6.0, v3.7.0 on Aug 24, 2022
  5. modified the milestones: v3.7.0, v3.7.1 on Feb 14, 2023
  6. modified the milestones: v3.7.1, v3.7.2 on Mar 4, 2023
  7. modified the milestones: v3.7.2, v3.7.3 on Jul 5, 2023
  8. modified the milestones: v3.7.3, v3.8.0 on Sep 9, 2023
  9. removed this from the v3.8.0 milestone on Sep 15, 2023
  10. oliviavanzandt commented on Nov 28, 2023

    @oliviavanzandt

    @blatr Hi, is this still an issue or has it been resolved?

  11. oliviavanzandt commented on Dec 4, 2023

    @oliviavanzandt

    @blatr @QuLogic @ksunden Hi, I am a student at CMU and for an end of the year project, my team has to pick an issue on matplotlib and try to fix it. We chose this issue. We were able to fix the example code above and get it to run without an error. We were wondering if this is a user error issue or a bug in the matplotlib code? Here is how we fixed the code for reproduction below:

    import matplotlib
    import matplotlib.pyplot as plt
    matplotlib.use("Agg")
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    import numpy as np
    import cv2
    
    def context_to_image_bgr(context):
        fig = context["fig"]
        w, h = map(int, fig.get_size_inches() * fig.get_dpi())
        true_w, true_h = np.round(fig.get_size_inches() * fig.get_dpi()).astype(int)
        canvas = context["canvas"]
        canvas.draw()
        image_1d = np.fromstring(canvas.tostring_rgb(), dtype="uint8")
        image_rgb = image_1d.reshape(h, w, 3)
        image_bgr = image_rgb[:, :, ::-1].copy()
        if (true_w, true_h) == (w,h):
            return image_bgr
        else:
            return cv2.resize(image_bgr, (true_w, true_h))
    
    dpi = 100
    h = 1708
    w = 2560
    height_inches = float(h) / dpi
    width_inches = float(w) / dpi
    
    fig = plt.figure(figsize=(width_inches, height_inches), dpi=dpi)
    plt.axes([0, 0, 1, 1])
    plt.axis("off")
    
    canvas = FigureCanvas(fig)
    
    context = {"fig": fig, "canvas": canvas}
    
    images = context_to_image_bgr(context)
    
    extent = (0, 2560, 1708, 0)
    plt.imshow(np.zeros((2560, 1708,3)), extent=extent)
    canvas.draw()
    fig.clear()
    plt.close(fig)
    
    original_image = np.fromstring(context_to_image_bgr(context), dtype="uint8").reshape(h, w, 3)
    print(original_image)
  12. ksunden commented on Dec 4, 2023

    @ksunden
    Member

    This is a problem in matplotlib (well, moreso just a problem in using floats for something that is then discretized)

    We are not interested in modifying the resultant image after the fact here

    >>> h, dpi
    (1708, 100)
    >>> h/dpi*dpi
    1707.9999999999998

    Is the fundamental problem (which is not even on MPL, directly).

    One fix, as mentioned previously, is to use round instead of int for these conversions... that has some knock-on effects that some test images may be changed which is annoying, but workable probably.

    I think another fix would be to have a set_size_pixels method that allows you to pass the int values in (and probably uses the dpi to compute the size in inches, since aspect ratio can change there) but have that be guaranteed to produce figures of that size (may be tricky though, as internally I think we use inches for a lot, and so not sure it'd be trivial to make the guarantee).

    See also #1369 #9226 (these are mostly about using metric units instead of inches, but pixels is another unit that might make sense)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions