从 C++ 嵌入式解释器捕获 python 窗口输出
Capturing python windowed output from C++ embedded interpreter
我正在使用 boost python 在 C++ 应用程序中嵌入一个 python 解释器。
(pybind11 也可以)
如果我从嵌入式解释器中调用 matplotlib,如下所示:
import matplotlib.pyplot as plt
import numpy as np
plt.plot([1,2,3,4],[1,4,9,16])
plt.show()
python 解释器打开一个新的 window(与我的应用程序的主要 window 分开)来显示 matplotlib 图。
我知道这是不可能的,但是有什么方法可以拦截它吗?
我希望能够捕获在这个单独的 window 中显示的像素,并在我的应用程序的主要 window.
的图形上下文中显示它们
我猜这是不可能的,因为我相信 window 是如何生成的。
但是想看看是否有人对此有任何见解。
您可以使用 hardcopy backends of matplotlib and save the pixels of the canvas to a string which can be exported to your C++ context 之一。以下是 python 代码:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot
fig = matplotlib.pyplot.figure()
ax = fig.add_subplot ( 111 )
ax.plot([1,2,3,4],[1,4,9,16])
fig.canvas.draw ()
w,h = fig.canvas.get_width_height() # width and height of the canvas
buf = fig.canvas.tostring_argb() # a byte string of type uint8
在您的 C++ 代码中,您可以使用变量 w
、h
和 buf
在您的主 window.
中显示图形
我正在使用 boost python 在 C++ 应用程序中嵌入一个 python 解释器。 (pybind11 也可以)
如果我从嵌入式解释器中调用 matplotlib,如下所示:
import matplotlib.pyplot as plt
import numpy as np
plt.plot([1,2,3,4],[1,4,9,16])
plt.show()
python 解释器打开一个新的 window(与我的应用程序的主要 window 分开)来显示 matplotlib 图。
我知道这是不可能的,但是有什么方法可以拦截它吗? 我希望能够捕获在这个单独的 window 中显示的像素,并在我的应用程序的主要 window.
的图形上下文中显示它们我猜这是不可能的,因为我相信 window 是如何生成的。 但是想看看是否有人对此有任何见解。
您可以使用 hardcopy backends of matplotlib and save the pixels of the canvas to a string which can be exported to your C++ context 之一。以下是 python 代码:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot
fig = matplotlib.pyplot.figure()
ax = fig.add_subplot ( 111 )
ax.plot([1,2,3,4],[1,4,9,16])
fig.canvas.draw ()
w,h = fig.canvas.get_width_height() # width and height of the canvas
buf = fig.canvas.tostring_argb() # a byte string of type uint8
在您的 C++ 代码中,您可以使用变量 w
、h
和 buf
在您的主 window.