在c++中引入python的matplotlib,实现画图功能

0、需要准备的:

opencv
python3
matplotlib
cmake
matplotlib-cpp包(git clone https://github.com/lava/matplotlib-cpp)
IDE:方便调试使用,大佬可忽略(author:vscode+cmake扩展+python扩展)

1、先说这里matplotlib中的内容:

在这里插入图片描述

inline void subplot(long nrows, long ncols, long plot_number)
{
    detail::_interpreter::get();

    // construct positional args
    PyObject* args = PyTuple_New(3);
    
    PyTuple_SetItem(args, 0, PyLong_FromLong(nrows));//把这里的float更换成和形参一样的long就可以了,当然你可以试试修改形参的类型为float
    PyTuple_SetItem(args, 1, PyLong_FromLong(ncols));
    PyTuple_SetItem(args, 2, PyLong_FromLong(plot_number));

    PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_subplot, args);
    if(!res) throw std::runtime_error("Call to subplot() failed.");

    Py_DECREF(args);
    Py_DECREF(res);
}
2、cmake中的内容:

主要的作用就是添加上matplotlib-cpp中需要包含的头文件,这里你还可以把numpy安装完,然后把安装好的库(numpy,matplotlib这里指python库)拷贝到python中。
拷贝的过程就是find -name python.h
cp puthon3.0 /usr/include/ 注意这里要拷贝的地址是cmake中默认的头文件地址,如果不知道可以在cmake里用message(include_directories)查看一下,因为这里头文件也可能是 /usr/local/include/
上面的工作就是把头文件放在cmake可以找到的位置。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

cmakelists.txt
cmake_minimum_required(VERSION 3.10)
project(test)
find_package(OpenCV REQUIRED) #new
include_directories(${CMAKE_CURRENT_BINARY_DIR})#new
include_directories(${OpenCV_INCLUDE_DIRS}) #new
set(PYTHON_HEADER_INLCUDE_DIRS "/usr/include/python3.10") #new注意这里的python版本以及地址
include_directories(include ${PYTHON_HEADER_INLCUDE_DIRS}) #new
aux_source_directory(. DIR_SRCS)#new 这里是把和cmakelists在同一个文件夹下的所有文件#define为DIR_SRCS,作用和project(),set()一致
add_executable(test ${DIR_SRCS})#new
target_link_libraries(test  ${OpenCV_LIBS}  libpython3.10.so)#new
3、实践一下吧:

.
├── build
├── CMakeLists.txt
├── matplotlibcpp.h
└── test.cpp

test.cpp:
#define _USE_MATH_DEFINES

#include <iostream>
#include <string>
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;

int main(int argc, char **argv) {
    std::vector<int> test_data;
    for (int i = 0; i < 20; i++) {
        test_data.push_back(i);
    }

    plt::bar(test_data);
    plt::show();

    return (0);
}

在这里插入图片描述

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值