forked from yagweb/pythonnetLab
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatplotlib.cs
More file actions
56 lines (47 loc) · 1.87 KB
/
Copy pathMatplotlib.cs
File metadata and controls
56 lines (47 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
namespace Python.Runtime
{
public class Matplotlib
{
public static void Initialize(string backend = null)
{
np = Py.Import("numpy");
matplotlib = Py.Import("matplotlib");
if (!String.IsNullOrEmpty(backend))
{
// backend must be set before pylab be imported
// It can not be changed after pylab be imported
PythonEngine.Exec($"import matplotlib;matplotlib.use('{backend}')");
}
plt = Py.Import("matplotlib.pylab");
PltFigureType = plt.GetAttr("Figure").Handle;
var io = Py.Import("io");
BytesIO = io.GetAttr("BytesIO");
PythonEngine.Exec("import matplotlib;print(matplotlib.get_backend())");
}
internal static PyObject np;
internal static PyObject matplotlib;
internal static PyObject plt;
internal static IntPtr PltFigureType;
internal static PyObject BytesIO;
public static byte[] SaveFigureToArray(PyObject fig, int dpi = 200, string format = "png")
{
if (fig.GetPythonType().Handle != PltFigureType)
{
throw new Exception("object is not a matplotlib Figure");
}
dynamic _np = np;
//buf = io.BytesIO()
dynamic buf = BytesIO.Invoke();
//fig.savefig(buf, dpi=__dpi__, format='png')
fig.InvokeMethod("savefig", new PyTuple(new PyObject[] { buf }), Py.kw("dpi", dpi, "format", format));
var buf_out = _np.array(buf.getbuffer(), Py.kw("dtype", Numpy.GetNumpyDataType(typeof(byte))));
var arr = Numpy.ToArray(buf_out);
return (byte[])arr;
}
public static string get_backend()
{
return matplotlib.InvokeMethod("get_backend").ToString();
}
}
}