python - 从 C++ 嵌入式解释器捕获 python 窗口输出
问题描述
我正在使用 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 解释器打开一个新窗口(与我的应用程序的主窗口分开)来显示 matplotlib 图。
我知道这是一个很长的镜头,但是有什么办法可以拦截吗?我希望能够捕获显示在这个单独窗口中的像素,并将它们显示在我的应用程序主窗口的图形上下文中。
我猜这是不可能的,因为我相信窗口正在生成。但想检查是否有人对此有任何见解。
解决方案
您可以使用 matplotlib 的硬拷贝后端之一,并将画布的像素保存到可以导出到 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
在主窗口中显示图形。
推荐阅读
- node.js - 如何仅在客户登录时显示客户记录/数据?
- python - 如何将python dict变成Curl
- python - 在 if / else 语句中创建循环
- java - 检查 nextInt() 中的十进制数输入
- docker - 树莓派 4 + Docker 运行多个 cpu
- python-3.x - 在 S3 中上传之前从 CSV 文件中的所有值中删除双引号
- html - 带有 ID 的元素
- angular - Angular (npm) 在 angular-devkit 中的现有目录前添加下划线并给出“无目录”(ENOENT) 错误
- c# - 来自 Unity3D 的 OpenCV dll 调用导致 FPS 下降
- python - 树莓派上的录音错误,输入溢出