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

Skip to content

Commit aac292b

Browse files
committed
added array and png helper funcs to mathtext
svn path=/trunk/matplotlib/; revision=5490
1 parent 8c44ac7 commit aac292b

7 files changed

Lines changed: 157 additions & 9 deletions

File tree

CHANGELOG

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
2008-06-12 Added some helper functions to the mathtext parser to
2+
return bitmap arrays or write pngs to make it easier to use
3+
mathtext outside the context of an mpl figure. modified
4+
the mathpng sphinxext to use the mathtext png save
5+
functionality
6+
17
2008-06-11 Use matplotlib.mathtext to render math expressions in
28
online docs - MGD
39

doc/sphinxext/mathpng.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -92,16 +92,19 @@ def latex2png(latex, name):
9292
os.system('dvipng -bgTransparent -Ttight --noghostscript -l10 ' +
9393
'-o %s math.dvi > /dev/null' % name)
9494

95+
96+
from matplotlib import rcParams
97+
from matplotlib.mathtext import MathTextParser
98+
rcParams['mathtext.fontset'] = 'cm'
99+
mathtext_parser = MathTextParser("Bitmap")
100+
101+
95102
# This uses mathtext to render the expression
96103
def latex2png(latex, filename):
97-
from matplotlib import rcParams
98-
from matplotlib import _png
99-
from matplotlib.mathtext import MathTextParser
100-
rcParams['mathtext.fontset'] = 'cm'
101-
mathtext_parser = MathTextParser("Bitmap")
102-
ftimage = mathtext_parser.parse("$%s$" % latex, 120)
103-
_png.write_png(ftimage.as_rgba_str(), ftimage.get_width(),
104-
ftimage.get_height(), filename)
104+
if os.path.exists(filename):
105+
return
106+
mathtext_parser.to_png(filename, "$%s$" % latex, dpi=120)
107+
105108

106109
# LaTeX to HTML translation stuff:
107110
def latex2html(node, source):

examples/api/mathtext_asarray.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""
2+
Load a mathtext image as numpy array
3+
"""
4+
5+
import numpy as np
6+
import matplotlib.mathtext as mathtext
7+
import matplotlib.pyplot as plt
8+
9+
parser = mathtext.MathTextParser("Bitmap")
10+
11+
parser.to_png('test2.png', r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} y\right)\right]$', color='green', fontsize=14, dpi=100)
12+
13+
14+
rgba = parser.to_rgba(r'IQ: $\sigma_i=15$', color='blue', fontsize=20, dpi=200)
15+
16+
fig = plt.figure()
17+
fig.figimage(rgba.astype(float)/255., 100, 100)
18+
19+
plt.show()

lib/matplotlib/mathtext.py

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@
180180
from warnings import warn
181181

182182
from numpy import inf, isinf
183-
183+
import numpy as np
184184
from matplotlib.pyparsing import Combine, Group, Optional, Forward, \
185185
Literal, OneOrMore, ZeroOrMore, ParseException, Empty, \
186186
ParseResults, Suppress, oneOf, StringEnd, ParseFatalException, \
@@ -197,6 +197,10 @@
197197
latex_to_standard, tex2uni, latex_to_cmex, stix_virtual_fonts
198198
from matplotlib import get_data_path, rcParams
199199

200+
201+
202+
import matplotlib.colors as mcolors
203+
import matplotlib._png as _png
200204
####################
201205

202206

@@ -2724,3 +2728,74 @@ def parse(self, s, dpi = 72, prop = None):
27242728
font_output.mathtext_backend = None
27252729

27262730
return result
2731+
2732+
def to_mask(self, texstr, dpi=120, fontsize=14):
2733+
"""
2734+
return an NxM uint8 alpha ubyte mask array of rasterized tex
2735+
2736+
''texstr''
2737+
A valid mathtext string, eg r'IQ: $\sigma_i=15$'
2738+
2739+
''dpi''
2740+
The dots-per-inch to render the text
2741+
2742+
''fontsize''
2743+
The font size in points
2744+
"""
2745+
assert(self._output=="bitmap")
2746+
prop = FontProperties(size=fontsize)
2747+
ftimage = self.parse(texstr, dpi=dpi, prop=prop)
2748+
2749+
x = ftimage.as_array()
2750+
return x
2751+
2752+
def to_rgba(self, texstr, color='black', dpi=120, fontsize=14):
2753+
"""
2754+
return an NxMx4 RGBA array of ubyte rasterized tex
2755+
2756+
''texstr''
2757+
A valid mathtext string, eg r'IQ: $\sigma_i=15$'
2758+
2759+
''color''
2760+
A valid matplotlib color argument
2761+
2762+
''dpi''
2763+
The dots-per-inch to render the text
2764+
2765+
''fontsize''
2766+
The font size in points
2767+
"""
2768+
x = self.to_mask(texstr, dpi=dpi, fontsize=fontsize)
2769+
2770+
r, g, b = mcolors.colorConverter.to_rgb(color)
2771+
RGBA = np.zeros((x.shape[0], x.shape[1], 4), dtype=np.uint8)
2772+
RGBA[:,:,0] = int(255*r)
2773+
RGBA[:,:,1] = int(255*g)
2774+
RGBA[:,:,2] = int(255*b)
2775+
RGBA[:,:,3] = x
2776+
return RGBA
2777+
2778+
def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
2779+
"""
2780+
2781+
''filename''
2782+
A writable filename or fileobject
2783+
2784+
''texstr''
2785+
A valid mathtext string, eg r'IQ: $\sigma_i=15$'
2786+
2787+
''color''
2788+
A valid matplotlib color argument
2789+
2790+
''dpi''
2791+
The dots-per-inch to render the text
2792+
2793+
''fontsize''
2794+
The font size in points
2795+
2796+
"""
2797+
2798+
rgba = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize)
2799+
numrows, numcols, tmp = rgba.shape
2800+
return _png.write_png(rgba.tostring(), numcols, numrows, filename)
2801+

setupext.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,7 @@ def add_agg_flags(module):
589589

590590
def add_ft2font_flags(module):
591591
'Add the module flags to ft2font extension'
592+
add_numpy_flags(module)
592593
if not get_pkgconfig(module, 'freetype2'):
593594
module.libraries.extend(['freetype', 'z'])
594595
add_base_flags(module)

src/ft2font.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
#include "mplutils.h"
33
#include <sstream>
44

5+
#define PY_ARRAY_TYPES_PREFIX NumPy
6+
#include "numpy/arrayobject.h"
7+
58
#define FIXED_MAJOR(val) (*((short *) &val+1))
69
#define FIXED_MINOR(val) (*((short *) &val+0))
710

@@ -251,6 +254,41 @@ FT2Image::py_as_str(const Py::Tuple & args) {
251254
);
252255
}
253256

257+
char FT2Image::as_array__doc__[] =
258+
"x = image.as_array()\n"
259+
"\n"
260+
"Return the image buffer as a width x height numpy array of ubyte \n"
261+
"\n"
262+
;
263+
Py::Object
264+
FT2Image::py_as_array(const Py::Tuple & args) {
265+
_VERBOSE("FT2Image::as_array");
266+
args.verify_length(0);
267+
268+
int dimensions[2];
269+
dimensions[0] = get_height(); //numrows
270+
dimensions[1] = get_width(); //numcols
271+
272+
273+
PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNewFromData(2, dimensions, PyArray_UBYTE, _buffer);
274+
275+
/*
276+
277+
PyArrayObject *A = (PyArrayObject *) PyArray_FromDims(2, dimensions, PyArray_UBYTE);
278+
279+
280+
unsigned char *src = _buffer;
281+
unsigned char *src_end = src + (dimensions[0] * dimensions[1]);
282+
unsigned char *dst = (unsigned char *)A->data;
283+
284+
while (src != src_end) {
285+
*dst++ = *src++;
286+
}
287+
*/
288+
289+
return Py::asObject((PyObject*)A);
290+
}
291+
254292
void FT2Image::makeRgbCopy() {
255293
if (!_isDirty)
256294
return;
@@ -1697,6 +1735,8 @@ FT2Image::init_type() {
16971735
FT2Image::draw_rect__doc__);
16981736
add_varargs_method("draw_rect_filled", &FT2Image::py_draw_rect_filled,
16991737
FT2Image::draw_rect_filled__doc__);
1738+
add_varargs_method("as_array", &FT2Image::py_as_array,
1739+
FT2Image::as_array__doc__);
17001740
add_varargs_method("as_str", &FT2Image::py_as_str,
17011741
FT2Image::as_str__doc__);
17021742
add_varargs_method("as_rgb_str", &FT2Image::py_as_rgb_str,
@@ -1834,6 +1874,7 @@ void
18341874
initft2font(void)
18351875
{
18361876
static ft2font_module* ft2font = new ft2font_module;
1877+
import_array();
18371878

18381879
Py::Dict d = ft2font->moduleDictionary();
18391880
d["SCALABLE"] = Py::Int(FT_FACE_FLAG_SCALABLE);
@@ -1885,5 +1926,6 @@ initft2font(void)
18851926
}
18861927

18871928
ft2font_module::~ft2font_module() {
1929+
18881930
FT_Done_FreeType( _ft2Library );
18891931
}

src/ft2font.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ class FT2Image : public Py::PythonExtension<FT2Image> {
4545
Py::Object py_draw_rect(const Py::Tuple & args);
4646
static char draw_rect_filled__doc__ [];
4747
Py::Object py_draw_rect_filled(const Py::Tuple & args);
48+
static char as_array__doc__ [];
49+
Py::Object py_as_array(const Py::Tuple & args);
4850
static char as_str__doc__ [];
4951
Py::Object py_as_str(const Py::Tuple & args);
5052
static char as_rgb_str__doc__ [];

0 commit comments

Comments
 (0)