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

Skip to content

Commit 0bc633b

Browse files
committed
Deprecate MathTextParser("bitmap") and associated APIs.
`MathTextParser("bitmap")` is rather low-level APIs to convert text strings to images. Instead, one can use a much more generic method, namely directly drawing to a new Figure() and saving with `bbox_inches="tight"`. Alternatively, if one really wants a single function call, there's still `mathtext.math_to_image`. Also fix the wx example to use light text colors when so directed by the system theme.
1 parent 79eca0e commit 0bc633b

File tree

7 files changed

+94
-54
lines changed

7 files changed

+94
-54
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
``MathTextParser("bitmap")`` is deprecated
2+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3+
4+
The associated APIs ``MathtextBackendBitmap``, ``MathTextParser.to_mask``,
5+
``MathTextParser.to_rgba``, ``MathTextParser.to_png``, and
6+
``MathTextParser.get_depth`` are likewise deprecated.
7+
8+
To convert a text string to an image, either directly draw the text to an
9+
empty `.Figure` and save the figure using a tight bbox, as demonstrated in
10+
:doc:`/gallery/text_labels_and_annotations/mathtext_asarray`, or use
11+
`.mathtext.math_to_image`.
Lines changed: 40 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,47 @@
11
"""
2-
===============================
3-
A mathtext image as numpy array
4-
===============================
5-
6-
Make images from LaTeX strings.
2+
=======================
3+
Convert texts to images
4+
=======================
75
"""
86

9-
import matplotlib.mathtext as mathtext
10-
import matplotlib.pyplot as plt
7+
from io import BytesIO
118

12-
parser = mathtext.MathTextParser("Bitmap")
13-
parser.to_png('test2.png',
14-
r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} '
15-
r'y\right)\right]$', color='green', fontsize=14, dpi=100)
9+
from matplotlib.figure import Figure
10+
import matplotlib.pyplot as plt
11+
from matplotlib.transforms import IdentityTransform
12+
13+
14+
def text_to_rgba(s, *, dpi, **kwargs):
15+
# To convert a text string to an image, we can:
16+
# - draw it on an empty and transparent figure;
17+
# - save the figure to a temporary buffer using ``bbox_inches="tight",
18+
# pad_inches=0`` which will pick the correct area to save;
19+
# - load the buffer using ``plt.imread``.
20+
#
21+
# (If desired, one can also directly save the image to the filesystem.)
22+
fig = Figure(facecolor="none")
23+
fig.text(0, 0, s, **kwargs)
24+
buf = BytesIO()
25+
fig.savefig(buf, dpi=dpi, format="png", bbox_inches="tight", pad_inches=0)
26+
buf.seek(0)
27+
rgba = plt.imread(buf)
28+
return rgba
1629

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

2231
fig = plt.figure()
23-
fig.figimage(rgba1, 100, 100)
24-
fig.figimage(rgba2, 100, 300)
32+
rgba1 = text_to_rgba(r"IQ: $\sigma_i=15$", color="blue", fontsize=20, dpi=200)
33+
rgba2 = text_to_rgba(r"some other string", color="red", fontsize=20, dpi=200)
34+
# One can then draw such text images to a Figure using `.Figure.figimage`.
35+
fig.figimage(rgba1, 100, 50)
36+
fig.figimage(rgba2, 100, 150)
37+
38+
# One can also directly draw texts to a figure with positioning
39+
# in pixel coordinates by using `.Figure.text` together with
40+
# `.transforms.IdentityTransform`.
41+
fig.text(100, 250, r"IQ: $\sigma_i=15$", color="blue", fontsize=20,
42+
transform=IdentityTransform())
43+
fig.text(100, 350, r"some other string", color="red", fontsize=20,
44+
transform=IdentityTransform())
2545

2646
plt.show()
2747

@@ -36,8 +56,7 @@
3656
# in this example:
3757

3858
import matplotlib
39-
matplotlib.mathtext
40-
matplotlib.mathtext.MathTextParser
41-
matplotlib.mathtext.MathTextParser.to_png
42-
matplotlib.mathtext.MathTextParser.to_rgba
4359
matplotlib.figure.Figure.figimage
60+
matplotlib.figure.Figure.text
61+
matplotlib.transforms.IdentityTransform
62+
matplotlib.image.imread

examples/user_interfaces/mathtext_wx_sgskip.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,36 +3,39 @@
33
MathText WX
44
===========
55
6-
Demonstrates how to convert mathtext to a wx.Bitmap for display in various
6+
Demonstrates how to convert (math)text to a wx.Bitmap for display in various
77
controls on wxPython.
88
"""
99

10-
import matplotlib
11-
matplotlib.use("WxAgg")
10+
from io import BytesIO
11+
1212
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
1313
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
1414
from matplotlib.figure import Figure
1515
import numpy as np
16-
1716
import wx
1817

1918
IS_GTK = 'wxGTK' in wx.PlatformInfo
2019
IS_WIN = 'wxMSW' in wx.PlatformInfo
2120

22-
############################################################
23-
# This is where the "magic" happens.
24-
from matplotlib.mathtext import MathTextParser
25-
mathtext_parser = MathTextParser("Bitmap")
26-
2721

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

3336
functions = [
3437
(r'$\sin(2 \pi x)$', lambda x: np.sin(2*np.pi*x)),
35-
(r'$\frac{4}{3}\pi x^3$', lambda x: (4.0/3.0)*np.pi*x**3),
38+
(r'$\frac{4}{3}\pi x^3$', lambda x: (4/3)*np.pi*x**3),
3639
(r'$\cos(2 \pi x)$', lambda x: np.cos(2*np.pi*x)),
3740
(r'$\log(x)$', lambda x: np.log(x))
3841
]

lib/matplotlib/contour.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -249,9 +249,9 @@ def get_label_width(self, lev, fmt, fsize):
249249
.get_text_width_height_descent(lev, fsize))
250250
elif ismath:
251251
if not hasattr(self, '_mathtext_parser'):
252-
self._mathtext_parser = mathtext.MathTextParser('bitmap')
253-
img, _ = self._mathtext_parser.parse(lev, dpi=72,
254-
prop=self.labelFontProps)
252+
self._mathtext_parser = mathtext.MathTextParser('agg')
253+
_, _, _, _, _, img, _ = self._mathtext_parser.parse(
254+
lev, dpi=72, prop=self.labelFontProps)
255255
_, lw = np.shape(img) # at dpi=72, the units are PostScript points
256256
else:
257257
# width is much less than "font size"

lib/matplotlib/mathtext.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ def get_hinting_type(self):
171171
return backend_agg.get_hinting_flag()
172172

173173

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

464+
@cbook.deprecated("3.4", alternative="mathtext.math_to_image")
463465
def to_mask(self, texstr, dpi=120, fontsize=14):
464466
r"""
467+
Convert a mathtext string to a grayscale array and depth.
468+
465469
Parameters
466470
----------
467471
texstr : str
@@ -483,8 +487,11 @@ def to_mask(self, texstr, dpi=120, fontsize=14):
483487
ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop)
484488
return np.asarray(ftimage), depth
485489

490+
@cbook.deprecated("3.4", alternative="mathtext.math_to_image")
486491
def to_rgba(self, texstr, color='black', dpi=120, fontsize=14):
487492
r"""
493+
Convert a mathtext string to a RGBA array and depth.
494+
488495
Parameters
489496
----------
490497
texstr : str
@@ -513,6 +520,7 @@ def to_rgba(self, texstr, color='black', dpi=120, fontsize=14):
513520
RGBA[:, :, 3] = x
514521
return RGBA, depth
515522

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

551+
@cbook.deprecated("3.4", alternative="mathtext.math_to_image")
543552
def get_depth(self, texstr, dpi=120, fontsize=14):
544553
r"""
554+
Get the depth of a mathtext string.
555+
545556
Parameters
546557
----------
547558
texstr : str

lib/matplotlib/sphinxext/mathmpl.py

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,7 @@
66
import sphinx
77

88
import matplotlib as mpl
9-
from matplotlib import cbook
10-
from matplotlib.mathtext import MathTextParser
11-
mathtext_parser = MathTextParser("Bitmap")
9+
from matplotlib import cbook, mathtext
1210

1311

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

1816

1917
def fontset_choice(arg):
20-
return directives.choice(arg, MathTextParser._font_type_mapping)
18+
return directives.choice(arg, mathtext.MathTextParser._font_type_mapping)
2119

2220

2321
def math_role(role, rawtext, text, lineno, inliner,
@@ -50,15 +48,12 @@ def run(self):
5048
def latex2png(latex, filename, fontset='cm'):
5149
latex = "$%s$" % latex
5250
with mpl.rc_context({'mathtext.fontset': fontset}):
53-
if Path(filename).exists():
54-
depth = mathtext_parser.get_depth(latex, dpi=100)
55-
else:
56-
try:
57-
depth = mathtext_parser.to_png(filename, latex, dpi=100)
58-
except Exception:
59-
cbook._warn_external(
60-
f"Could not render math expression {latex}")
61-
depth = 0
51+
try:
52+
depth = mathtext.math_to_image(
53+
latex, filename, dpi=100, format="png")
54+
except Exception:
55+
cbook._warn_external(f"Could not render math expression {latex}")
56+
depth = 0
6257
return depth
6358

6459

lib/matplotlib/tests/test_mathtext.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import matplotlib as mpl
99
from matplotlib.testing.decorators import check_figures_equal, image_comparison
1010
import matplotlib.pyplot as plt
11-
from matplotlib import mathtext
11+
from matplotlib import cbook, mathtext
1212

1313

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

358358

359359
def test_mathtext_to_png(tmpdir):
360-
mt = mathtext.MathTextParser('bitmap')
361-
mt.to_png(str(tmpdir.join('example.png')), '$x^2$')
362-
mt.to_png(io.BytesIO(), '$x^2$')
360+
with cbook._suppress_matplotlib_deprecation_warning():
361+
mt = mathtext.MathTextParser('bitmap')
362+
mt.to_png(str(tmpdir.join('example.png')), '$x^2$')
363+
mt.to_png(io.BytesIO(), '$x^2$')
363364

364365

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

0 commit comments

Comments
 (0)