|
From: <jd...@us...> - 2008-06-12 19:14:25
|
Revision: 5490
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5490&view=rev
Author: jdh2358
Date: 2008-06-12 12:14:21 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
added array and png helper funcs to mathtext
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/doc/sphinxext/mathpng.py
trunk/matplotlib/lib/matplotlib/mathtext.py
trunk/matplotlib/setupext.py
trunk/matplotlib/src/ft2font.cpp
trunk/matplotlib/src/ft2font.h
Added Paths:
-----------
trunk/matplotlib/examples/api/mathtext_asarray.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-06-12 18:05:16 UTC (rev 5489)
+++ trunk/matplotlib/CHANGELOG 2008-06-12 19:14:21 UTC (rev 5490)
@@ -1,3 +1,9 @@
+2008-06-12 Added some helper functions to the mathtext parser to
+ return bitmap arrays or write pngs to make it easier to use
+ mathtext outside the context of an mpl figure. modified
+ the mathpng sphinxext to use the mathtext png save
+ functionality
+
2008-06-11 Use matplotlib.mathtext to render math expressions in
online docs - MGD
Modified: trunk/matplotlib/doc/sphinxext/mathpng.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/mathpng.py 2008-06-12 18:05:16 UTC (rev 5489)
+++ trunk/matplotlib/doc/sphinxext/mathpng.py 2008-06-12 19:14:21 UTC (rev 5490)
@@ -92,17 +92,20 @@
os.system('dvipng -bgTransparent -Ttight --noghostscript -l10 ' +
'-o %s math.dvi > /dev/null' % name)
+
+from matplotlib import rcParams
+from matplotlib.mathtext import MathTextParser
+rcParams['mathtext.fontset'] = 'cm'
+mathtext_parser = MathTextParser("Bitmap")
+
+
# This uses mathtext to render the expression
def latex2png(latex, filename):
- from matplotlib import rcParams
- from matplotlib import _png
- from matplotlib.mathtext import MathTextParser
- rcParams['mathtext.fontset'] = 'cm'
- mathtext_parser = MathTextParser("Bitmap")
- ftimage = mathtext_parser.parse("$%s$" % latex, 120)
- _png.write_png(ftimage.as_rgba_str(), ftimage.get_width(),
- ftimage.get_height(), filename)
+ if os.path.exists(filename):
+ return
+ mathtext_parser.to_png(filename, "$%s$" % latex, dpi=120)
+
# LaTeX to HTML translation stuff:
def latex2html(node, source):
inline = isinstance(node.parent, nodes.TextElement)
Added: trunk/matplotlib/examples/api/mathtext_asarray.py
===================================================================
--- trunk/matplotlib/examples/api/mathtext_asarray.py (rev 0)
+++ trunk/matplotlib/examples/api/mathtext_asarray.py 2008-06-12 19:14:21 UTC (rev 5490)
@@ -0,0 +1,19 @@
+"""
+Load a mathtext image as numpy array
+"""
+
+import numpy as np
+import matplotlib.mathtext as mathtext
+import matplotlib.pyplot as plt
+
+parser = mathtext.MathTextParser("Bitmap")
+
+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)
+
+
+rgba = parser.to_rgba(r'IQ: $\sigma_i=15$', color='blue', fontsize=20, dpi=200)
+
+fig = plt.figure()
+fig.figimage(rgba.astype(float)/255., 100, 100)
+
+plt.show()
Modified: trunk/matplotlib/lib/matplotlib/mathtext.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-12 18:05:16 UTC (rev 5489)
+++ trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-12 19:14:21 UTC (rev 5490)
@@ -180,7 +180,7 @@
from warnings import warn
from numpy import inf, isinf
-
+import numpy as np
from matplotlib.pyparsing import Combine, Group, Optional, Forward, \
Literal, OneOrMore, ZeroOrMore, ParseException, Empty, \
ParseResults, Suppress, oneOf, StringEnd, ParseFatalException, \
@@ -197,6 +197,10 @@
latex_to_standard, tex2uni, latex_to_cmex, stix_virtual_fonts
from matplotlib import get_data_path, rcParams
+
+
+import matplotlib.colors as mcolors
+import matplotlib._png as _png
####################
@@ -2724,3 +2728,74 @@
font_output.mathtext_backend = None
return result
+
+ def to_mask(self, texstr, dpi=120, fontsize=14):
+ """
+ return an NxM uint8 alpha ubyte mask array of rasterized tex
+
+ ''texstr''
+ A valid mathtext string, eg r'IQ: $\sigma_i=15$'
+
+ ''dpi''
+ The dots-per-inch to render the text
+
+ ''fontsize''
+ The font size in points
+ """
+ assert(self._output=="bitmap")
+ prop = FontProperties(size=fontsize)
+ ftimage = self.parse(texstr, dpi=dpi, prop=prop)
+
+ x = ftimage.as_array()
+ return x
+
+ def to_rgba(self, texstr, color='black', dpi=120, fontsize=14):
+ """
+ return an NxMx4 RGBA array of ubyte rasterized tex
+
+ ''texstr''
+ A valid mathtext string, eg r'IQ: $\sigma_i=15$'
+
+ ''color''
+ A valid matplotlib color argument
+
+ ''dpi''
+ The dots-per-inch to render the text
+
+ ''fontsize''
+ The font size in points
+ """
+ x = self.to_mask(texstr, dpi=dpi, fontsize=fontsize)
+
+ r, g, b = mcolors.colorConverter.to_rgb(color)
+ RGBA = np.zeros((x.shape[0], x.shape[1], 4), dtype=np.uint8)
+ RGBA[:,:,0] = int(255*r)
+ RGBA[:,:,1] = int(255*g)
+ RGBA[:,:,2] = int(255*b)
+ RGBA[:,:,3] = x
+ return RGBA
+
+ def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
+ """
+
+ ''filename''
+ A writable filename or fileobject
+
+ ''texstr''
+ A valid mathtext string, eg r'IQ: $\sigma_i=15$'
+
+ ''color''
+ A valid matplotlib color argument
+
+ ''dpi''
+ The dots-per-inch to render the text
+
+ ''fontsize''
+ The font size in points
+
+ """
+
+ rgba = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize)
+ numrows, numcols, tmp = rgba.shape
+ return _png.write_png(rgba.tostring(), numcols, numrows, filename)
+
Modified: trunk/matplotlib/setupext.py
===================================================================
--- trunk/matplotlib/setupext.py 2008-06-12 18:05:16 UTC (rev 5489)
+++ trunk/matplotlib/setupext.py 2008-06-12 19:14:21 UTC (rev 5490)
@@ -589,6 +589,7 @@
def add_ft2font_flags(module):
'Add the module flags to ft2font extension'
+ add_numpy_flags(module)
if not get_pkgconfig(module, 'freetype2'):
module.libraries.extend(['freetype', 'z'])
add_base_flags(module)
Modified: trunk/matplotlib/src/ft2font.cpp
===================================================================
--- trunk/matplotlib/src/ft2font.cpp 2008-06-12 18:05:16 UTC (rev 5489)
+++ trunk/matplotlib/src/ft2font.cpp 2008-06-12 19:14:21 UTC (rev 5490)
@@ -2,6 +2,9 @@
#include "mplutils.h"
#include <sstream>
+#define PY_ARRAY_TYPES_PREFIX NumPy
+#include "numpy/arrayobject.h"
+
#define FIXED_MAJOR(val) (*((short *) &val+1))
#define FIXED_MINOR(val) (*((short *) &val+0))
@@ -251,6 +254,41 @@
);
}
+char FT2Image::as_array__doc__[] =
+"x = image.as_array()\n"
+"\n"
+"Return the image buffer as a width x height numpy array of ubyte \n"
+"\n"
+;
+Py::Object
+FT2Image::py_as_array(const Py::Tuple & args) {
+ _VERBOSE("FT2Image::as_array");
+ args.verify_length(0);
+
+ int dimensions[2];
+ dimensions[0] = get_height(); //numrows
+ dimensions[1] = get_width(); //numcols
+
+
+ PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNewFromData(2, dimensions, PyArray_UBYTE, _buffer);
+
+ /*
+
+ PyArrayObject *A = (PyArrayObject *) PyArray_FromDims(2, dimensions, PyArray_UBYTE);
+
+
+ unsigned char *src = _buffer;
+ unsigned char *src_end = src + (dimensions[0] * dimensions[1]);
+ unsigned char *dst = (unsigned char *)A->data;
+
+ while (src != src_end) {
+ *dst++ = *src++;
+ }
+ */
+
+ return Py::asObject((PyObject*)A);
+}
+
void FT2Image::makeRgbCopy() {
if (!_isDirty)
return;
@@ -1697,6 +1735,8 @@
FT2Image::draw_rect__doc__);
add_varargs_method("draw_rect_filled", &FT2Image::py_draw_rect_filled,
FT2Image::draw_rect_filled__doc__);
+ add_varargs_method("as_array", &FT2Image::py_as_array,
+ FT2Image::as_array__doc__);
add_varargs_method("as_str", &FT2Image::py_as_str,
FT2Image::as_str__doc__);
add_varargs_method("as_rgb_str", &FT2Image::py_as_rgb_str,
@@ -1834,6 +1874,7 @@
initft2font(void)
{
static ft2font_module* ft2font = new ft2font_module;
+ import_array();
Py::Dict d = ft2font->moduleDictionary();
d["SCALABLE"] = Py::Int(FT_FACE_FLAG_SCALABLE);
@@ -1885,5 +1926,6 @@
}
ft2font_module::~ft2font_module() {
+
FT_Done_FreeType( _ft2Library );
}
Modified: trunk/matplotlib/src/ft2font.h
===================================================================
--- trunk/matplotlib/src/ft2font.h 2008-06-12 18:05:16 UTC (rev 5489)
+++ trunk/matplotlib/src/ft2font.h 2008-06-12 19:14:21 UTC (rev 5490)
@@ -45,6 +45,8 @@
Py::Object py_draw_rect(const Py::Tuple & args);
static char draw_rect_filled__doc__ [];
Py::Object py_draw_rect_filled(const Py::Tuple & args);
+ static char as_array__doc__ [];
+ Py::Object py_as_array(const Py::Tuple & args);
static char as_str__doc__ [];
Py::Object py_as_str(const Py::Tuple & args);
static char as_rgb_str__doc__ [];
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|