c ++ python draw 3D graphics calls

python plot.py

#coding=utf-8
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
def plot():
    mpl.rcParams['legend.fontsize'] = 10 #字体尺寸
    fig = plt.figure()#创建一个图片
    ax = fig.gca(projection='3d')#通过将关键字projection='3d'应用到坐标轴对象上来实现三维绘图
    # linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
    # 作用为:在规定的时间内,返回固定间隔的数据。他将返回“num”个等间距的样本,在区间[`start`, `stop`]中。其中,区间的结束端点可以被排除在外。
    theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
    z = np.linspace(-2, 2, 100)
    r = z**2 + 1
    x = r * np.sin(theta)
    y = r * np.cos(theta)
    ax.plot(x, y, z, label='parametric curve')
    ax.legend()#画出图列
    # loc: 表示位置,包括'upper right','upper left','lower right','lower left'等
    # bbox_to_anchor: 表示legend距离图形之间的距离,当出现图形与legend重叠时,可使用bbox_to_anchor进行调整legend的位置
    # 由两个参数决定,第一个参数为legend距离左边的距离,第二个参数为距离下面的距离
    #'upper right'=1;'upper left'=2;'lower left'=3;'lower right'=4; 0 自适应找位置
    #ncol 图例的列数
    plt.show()#显示

c ++ program

#include <iostream>

#include <Python.h>

using namespace std;

int main(int)
{
Py_Initialize();//-初始化python解释器
if(!Py_IsInitialized())
 {
  PyRun_SimpleString("print 'inital error!' ");
  return -1;
 }
PyRun_SimpleString("print 'inital ok!' ");
PyRun_SimpleString("import sys");//--相当于python中的import sys语句,sys是和解释器打交道的
PyRun_SimpleString("sys.path.append('./')"); //指定pytest.py所在的目录
PyRun_SimpleString("sys.argv = ['python.py']");
PyObject *pName =NULL;
PyObject *pMoudle = NULL;//--存储要调用的python模块
PyObject *pFunc = NULL;//--存储要调用的函数
pName = PyString_FromString("plot1"); //指定要导入的文件名
pMoudle = PyImport_Import(pName);//--利用导入文件函数将helloWorld.py函数导入
if(pMoudle == NULL)
 {
  PyRun_SimpleString("print 'PyImport_Import error!' ");
  return -1;
 }
pFunc = PyObject_GetAttrString(pMoudle,"plot");//--是在python引用模块helloWorld.py中查找hello函数
PyObject_CallObject(pFunc,NULL);//--调用hello函数

Py_Finalize();//--清理python环境释放资源
return 0;
} 

Write CMakeLists

cmake_minimum_required(VERSION 3.1)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)

project(plot_project)


#添加头文件搜索路径
include_directories(/usr/include/python2.7)#添加头文件目录,相当于g++ -I参数
link_directories(/usr/include/python2.7)#动态链接库或静态链接库的搜索路径,相当于gcc的-L参数
set(OpenCV_DIR /home/xiaoyuer/myopencv/opencv)
#寻找依赖功能包
find_package(OpenCV   REQUIRED)
#add_executable(1 1.cpp)
add_executable(c++_python c++_python.cpp)
#添加需要链接的共享库
#target_link_libraries(1 PRIVATE ${OpenCV_LIBS} python2.7) #添加链接库,相同于指定gcc -l参数
target_link_libraries(c++_python PRIVATE ${OpenCV_LIBS} python2.7)

Compile and run

Here Insert Picture Description

Published 34 original articles · won praise 2 · Views 2323

Guess you like

Origin blog.csdn.net/weixin_44088559/article/details/105201036