Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Deprecate MathTextParser("bitmap") and associated APIs. #18591

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions doc/api/next_api_changes/deprecations/18591-AL.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
``MathTextParser("bitmap")`` is deprecated
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The associated APIs ``MathtextBackendBitmap``, ``MathTextParser.to_mask``,
``MathTextParser.to_rgba``, ``MathTextParser.to_png``, and
``MathTextParser.get_depth`` are likewise deprecated.

To convert a text string to an image, either directly draw the text to an
empty `.Figure` and save the figure using a tight bbox, as demonstrated in
:doc:`/gallery/text_labels_and_annotations/mathtext_asarray`, or use
`.mathtext.math_to_image`.

When using `.math_to_image`, text color can be set with e.g.::

with plt.rc_context({"text.color": "tab:blue"}):
mathtext.math_to_image(text, filename)

and an RGBA array can be obtained with e.g.::

from io import BytesIO
buf = BytesIO()
mathtext.math_to_image(text, buf, format="png")
buf.seek(0)
rgba = plt.imread(buf)
61 changes: 40 additions & 21 deletions examples/text_labels_and_annotations/mathtext_asarray.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,47 @@
"""
===============================
A mathtext image as numpy array
===============================

Make images from LaTeX strings.
=======================
Convert texts to images
=======================
"""

import matplotlib.mathtext as mathtext
import matplotlib.pyplot as plt
from io import BytesIO

parser = mathtext.MathTextParser("Bitmap")
parser.to_png('test2.png',
r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} '
r'y\right)\right]$', color='green', fontsize=14, dpi=100)
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from matplotlib.transforms import IdentityTransform


def text_to_rgba(s, *, dpi, **kwargs):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not use math_to_image here?

# To convert a text string to an image, we can:
# - draw it on an empty and transparent figure;
# - save the figure to a temporary buffer using ``bbox_inches="tight",
# pad_inches=0`` which will pick the correct area to save;
# - load the buffer using ``plt.imread``.
#
# (If desired, one can also directly save the image to the filesystem.)
fig = Figure(facecolor="none")
fig.text(0, 0, s, **kwargs)
buf = BytesIO()
fig.savefig(buf, dpi=dpi, format="png", bbox_inches="tight", pad_inches=0)
buf.seek(0)
rgba = plt.imread(buf)
return rgba

rgba1, depth1 = parser.to_rgba(
r'IQ: $\sigma_i=15$', color='blue', fontsize=20, dpi=200)
rgba2, depth2 = parser.to_rgba(
r'some other string', color='red', fontsize=20, dpi=200)

fig = plt.figure()
fig.figimage(rgba1, 100, 100)
fig.figimage(rgba2, 100, 300)
rgba1 = text_to_rgba(r"IQ: $\sigma_i=15$", color="blue", fontsize=20, dpi=200)
rgba2 = text_to_rgba(r"some other string", color="red", fontsize=20, dpi=200)
# One can then draw such text images to a Figure using `.Figure.figimage`.
fig.figimage(rgba1, 100, 50)
fig.figimage(rgba2, 100, 150)

# One can also directly draw texts to a figure with positioning
# in pixel coordinates by using `.Figure.text` together with
# `.transforms.IdentityTransform`.
fig.text(100, 250, r"IQ: $\sigma_i=15$", color="blue", fontsize=20,
transform=IdentityTransform())
fig.text(100, 350, r"some other string", color="red", fontsize=20,
transform=IdentityTransform())

plt.show()

Expand All @@ -36,8 +56,7 @@
# in this example:

import matplotlib
matplotlib.mathtext
matplotlib.mathtext.MathTextParser
matplotlib.mathtext.MathTextParser.to_png
matplotlib.mathtext.MathTextParser.to_rgba
matplotlib.figure.Figure.figimage
matplotlib.figure.Figure.text
matplotlib.transforms.IdentityTransform
matplotlib.image.imread
29 changes: 16 additions & 13 deletions examples/user_interfaces/mathtext_wx_sgskip.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,39 @@
MathText WX
===========

Demonstrates how to convert mathtext to a wx.Bitmap for display in various
Demonstrates how to convert (math)text to a wx.Bitmap for display in various
controls on wxPython.
"""

import matplotlib
matplotlib.use("WxAgg")
from io import BytesIO

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.figure import Figure
import numpy as np

import wx

IS_GTK = 'wxGTK' in wx.PlatformInfo
IS_WIN = 'wxMSW' in wx.PlatformInfo

############################################################
# This is where the "magic" happens.
from matplotlib.mathtext import MathTextParser
mathtext_parser = MathTextParser("Bitmap")


def mathtext_to_wxbitmap(s):
rgba, depth = mathtext_parser.to_rgba(s, dpi=150, fontsize=10)
return wx.Bitmap.FromBufferRGBA(rgba.shape[1], rgba.shape[0], rgba)
############################################################
# We draw the text at position (0, 0) but then rely on
# ``facecolor="none"`` and ``bbox_inches="tight", pad_inches=0`` to get an
# transparent mask that is then loaded into a wx.Bitmap.
fig = Figure(facecolor="none")
text_color = (
np.array(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)) / 255)
fig.text(0, 0, s, fontsize=10, color=text_color)
buf = BytesIO()
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight", pad_inches=0)
s = buf.getvalue()
return wx.Bitmap.NewFromPNGData(s, len(s))


functions = [
(r'$\sin(2 \pi x)$', lambda x: np.sin(2*np.pi*x)),
(r'$\frac{4}{3}\pi x^3$', lambda x: (4.0/3.0)*np.pi*x**3),
(r'$\frac{4}{3}\pi x^3$', lambda x: (4/3)*np.pi*x**3),
(r'$\cos(2 \pi x)$', lambda x: np.cos(2*np.pi*x)),
(r'$\log(x)$', lambda x: np.log(x))
]
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,9 +249,9 @@ def get_label_width(self, lev, fmt, fsize):
.get_text_width_height_descent(lev, fsize))
elif ismath:
if not hasattr(self, '_mathtext_parser'):
self._mathtext_parser = mathtext.MathTextParser('bitmap')
img, _ = self._mathtext_parser.parse(lev, dpi=72,
prop=self.labelFontProps)
self._mathtext_parser = mathtext.MathTextParser('agg')
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this specific use is going away via #16171.

_, _, _, _, _, img, _ = self._mathtext_parser.parse(
lev, dpi=72, prop=self.labelFontProps)
_, lw = np.shape(img) # at dpi=72, the units are PostScript points
else:
# width is much less than "font size"
Expand Down
11 changes: 11 additions & 0 deletions lib/matplotlib/mathtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ def get_hinting_type(self):
return backend_agg.get_hinting_flag()


@cbook.deprecated("3.4", alternative="mathtext.math_to_image")
class MathtextBackendBitmap(MathtextBackendAgg):
def get_results(self, box, used_characters):
ox, oy, width, height, depth, image, characters = \
Expand Down Expand Up @@ -460,8 +461,11 @@ def _parse_cached(self, s, dpi, prop, force_standard_ps_fonts):
font_output.set_canvas_size(box.width, box.height, box.depth)
return font_output.get_results(box)

@cbook.deprecated("3.4", alternative="mathtext.math_to_image")
def to_mask(self, texstr, dpi=120, fontsize=14):
r"""
Convert a mathtext string to a grayscale array and depth.

Parameters
----------
texstr : str
Expand All @@ -483,8 +487,11 @@ def to_mask(self, texstr, dpi=120, fontsize=14):
ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop)
return np.asarray(ftimage), depth

@cbook.deprecated("3.4", alternative="mathtext.math_to_image")
def to_rgba(self, texstr, color='black', dpi=120, fontsize=14):
r"""
Convert a mathtext string to an RGBA array and depth.

Parameters
----------
texstr : str
Expand Down Expand Up @@ -513,6 +520,7 @@ def to_rgba(self, texstr, color='black', dpi=120, fontsize=14):
RGBA[:, :, 3] = x
return RGBA, depth

@cbook.deprecated("3.4", alternative="mathtext.math_to_image")
def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
r"""
Render a tex expression to a PNG file.
Expand Down Expand Up @@ -540,8 +548,11 @@ def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
Image.fromarray(rgba).save(filename, format="png")
return depth

@cbook.deprecated("3.4", alternative="mathtext.math_to_image")
def get_depth(self, texstr, dpi=120, fontsize=14):
r"""
Get the depth of a mathtext string.

Parameters
----------
texstr : str
Expand Down
21 changes: 8 additions & 13 deletions lib/matplotlib/sphinxext/mathmpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
import sphinx

import matplotlib as mpl
from matplotlib import cbook
from matplotlib.mathtext import MathTextParser
mathtext_parser = MathTextParser("Bitmap")
from matplotlib import cbook, mathtext


# Define LaTeX math node:
Expand All @@ -17,7 +15,7 @@ class latex_math(nodes.General, nodes.Element):


def fontset_choice(arg):
return directives.choice(arg, MathTextParser._font_type_mapping)
return directives.choice(arg, mathtext.MathTextParser._font_type_mapping)


def math_role(role, rawtext, text, lineno, inliner,
Expand Down Expand Up @@ -50,15 +48,12 @@ def run(self):
def latex2png(latex, filename, fontset='cm'):
latex = "$%s$" % latex
with mpl.rc_context({'mathtext.fontset': fontset}):
if Path(filename).exists():
depth = mathtext_parser.get_depth(latex, dpi=100)
else:
try:
depth = mathtext_parser.to_png(filename, latex, dpi=100)
except Exception:
cbook._warn_external(
f"Could not render math expression {latex}")
depth = 0
try:
depth = mathtext.math_to_image(
latex, filename, dpi=100, format="png")
except Exception:
cbook._warn_external(f"Could not render math expression {latex}")
depth = 0
return depth


Expand Down
9 changes: 5 additions & 4 deletions lib/matplotlib/tests/test_mathtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import matplotlib as mpl
from matplotlib.testing.decorators import check_figures_equal, image_comparison
import matplotlib.pyplot as plt
from matplotlib import mathtext
from matplotlib import cbook, mathtext


# If test is removed, use None as placeholder
Expand Down Expand Up @@ -357,9 +357,10 @@ def test_math_to_image(tmpdir):


def test_mathtext_to_png(tmpdir):
mt = mathtext.MathTextParser('bitmap')
mt.to_png(str(tmpdir.join('example.png')), '$x^2$')
mt.to_png(io.BytesIO(), '$x^2$')
with cbook._suppress_matplotlib_deprecation_warning():
mt = mathtext.MathTextParser('bitmap')
mt.to_png(str(tmpdir.join('example.png')), '$x^2$')
mt.to_png(io.BytesIO(), '$x^2$')


@image_comparison(baseline_images=['math_fontfamily_image.png'],
Expand Down