当前位置: 首页 > news >正文

win10 mingw 调用python

ubuntu调用pythonhttps://blog.csdn.net/qq_39942341/article/details/129333969

我这里mingw是用msys2的
opencv也是msys2装的
安装msys2和opencv可以参考这个https://blog.csdn.net/qq_39942341/article/details/129380197?spm=1001.2014.3001.5502

环境变量里加入python路径,例如D:\Miniconda3\envs\DL

D:\Miniconda3\envs\DL\libs里,python37.lib复制一份改成python37_d.lib
在这里插入图片描述

有个玄学的问题,我用不了imgaug这个库

opencv+numpy+pytorch

main.cpp

load_model
加载模型

get_predict_xy
用C++的opencv读图片,转numpy传入python
python再用pytorch预测,返回一个numpy

simple_test
用C++的opencv读图片,转numpy传入python
python直接传回来给C++,转opencv

顺带提一下,import_array()一定要写

#include <Python.h>
#include <iostream>
#include <string>
#include <numpy/arrayobject.h>
#include <opencv2/opencv.hpp>void load_model(PyObject* pModule, const std::string& model_path){PyObject* init_model = PyObject_GetAttrString(pModule, "init_model");if (NULL == init_model || 0 == PyCallable_Check(init_model)) {std::cout << "not found function init_model" << std::endl;exit(-1);}PyObject *pArgs = PyTuple_New(1);PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", model_path.c_str()));PyObject* result = PyObject_CallObject(init_model, pArgs);if(NULL == result){std::cout << "init_model failed" << std::endl;exit(-1);}int return_value = -1;PyArg_Parse(result, "i", &return_value);std::cout<<"returned "<<return_value<<std::endl;
}void get_predict_xy(PyObject* pModule, const std::string& img_path){cv::Mat img = cv::imread(img_path, 0);PyObject* predict = PyObject_GetAttrString(pModule, "get_predict_xy");if (NULL == predict || 0 == PyCallable_Check(predict)) {std::cout << "not found function get_predict_xy" << std::endl;exit(-1);}npy_intp dims[] = {img.rows, img.cols};PyObject* pValue = PyArray_SimpleNewFromData(2, dims, NPY_UINT8, img.data);PyObject *pArgs = PyTuple_New(1);// PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", img_path.c_str()));PyTuple_SetItem(pArgs, 0, pValue);PyObject* result = PyEval_CallObject(predict, pArgs);if(NULL == result){std::cout << "get_predict_xy failed" << std::endl;exit(-1);}if(!PyArray_Check(result)){//Nonestd::cout << "didn't return numpy" << std::endl;exit(-1);}PyArrayObject* ret_array;PyArray_OutputConverter(result, &ret_array);if(2 != PyArray_NDIM(ret_array)){exit(-1);}npy_intp* shape = PyArray_SHAPE(ret_array);int n = shape[0];int m = shape[1];cv::Mat return_key_points(n,m,CV_32F,PyArray_DATA(ret_array));for(int i = 0; i < n; ++i){for(int j = 0; j < m; ++j){int* cur = reinterpret_cast<int*>(PyArray_GETPTR2(ret_array, i, j));std::cout<<*cur<<' ';}std::cout<<std::endl;}//PyArray_GETPTR2
}void simple_test(PyObject* pModule, const std::string& img_path){cv::Mat img = cv::imread(img_path, 0);PyObject* predict = PyObject_GetAttrString(pModule, "simple_test");if (NULL == predict || 0 == PyCallable_Check(predict)) {std::cout << "not found function simple_test" << std::endl;exit(-1);}npy_intp dims[] = {img.rows, img.cols};PyObject* pValue = PyArray_SimpleNewFromData(2, dims, NPY_UINT8, img.data);PyObject *pArgs = PyTuple_New(1);// PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", img_path.c_str()));PyTuple_SetItem(pArgs, 0, pValue);PyObject* result = PyEval_CallObject(predict, pArgs);if(NULL == result){std::cout << "simple_test failed" << std::endl;exit(-1);}if(!PyArray_Check(result)){//Nonestd::cout << "didn't return numpy" << std::endl;exit(-1);}PyArrayObject* ret_array;PyArray_OutputConverter(result, &ret_array);if(2 != PyArray_NDIM(ret_array)){exit(-1);}npy_intp* shape = PyArray_SHAPE(ret_array);int n = shape[0];int m = shape[1];cv::Mat return_img(n,m,CV_8UC1,PyArray_DATA(ret_array));// cv::imshow("test", return_img);// cv::waitKey(0);// cv::destroyAllWindows();for(int i = 0; i < n; ++i){uchar* data1 = img.ptr<uchar>(i);uchar* data2 = return_img.ptr<uchar>(i);for(int j = 0; j < m; ++j){if(data1[j] != data2[j]){std::cout<<"not equal"<<std::endl;return;}}}std::cout<<"equal"<<std::endl;
}int main() {Py_SetPythonHome(L"D:\\Miniconda3\\envs\\DL");Py_Initialize();if (0 == Py_IsInitialized()) {std::cout << "python init fail" << std::endl;return -1;}import_array();PyRun_SimpleString("import sys");PyRun_SimpleString("import os");PyRun_SimpleString("print(os.path.abspath('.'))");PyRun_SimpleString("sys.path.append('../python_script')");//相当于importPyObject* pModule = PyImport_ImportModule("predict");if (NULL == pModule) {std::cout << "module not found" << std::endl;return -1;}simple_test(pModule, "../python_script/001.bmp");load_model(pModule, "../python_script/best.pth");get_predict_xy(pModule, "../python_script/001.bmp");get_predict_xy(pModule, "../python_script/001.bmp");Py_Finalize();return 0;
}

predict.py
UNet我没放出来

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import os
import numpy as npfrom model.u2net import UNet
import torch
from cv2 import cv2#import imgaug.augmenters as iaamodel = UNet(in_channels=1, out_channels=19)
device = torch.device('cuda:0')# augmentation = iaa.Sequential([
#     iaa.Resize({"width": 416, "height": 512})
# ])def init_model(path):global model, deviceif not os.path.exists(path):print(f'not found {os.path.abspath(path)}')return -1model_state_dict = torch.load(path)model.load_state_dict(model_state_dict)model = model.to(device)return 0def get_img_aug(img):# global augmentationprint('----get_img_aug------')print(img.shape)print('------------------')# img = cv2.imread(path, 0)  # 2490*1935# img_aug = augmentation(image=img)img_aug = cv2.resize(img, (416, 512), interpolation=cv2.INTER_LINEAR)img_aug = (img_aug - img_aug.min()) / (img_aug.max() - img_aug.min())img_aug = torch.FloatTensor(img_aug).unsqueeze(0).unsqueeze(0)  # torch.Size([1, 1, 512, 416])return img_augdef get_heatmap_coordination_batch_numpy(heatmap):"""get heatmap coordination by batch:param heatmap: (B,C,H,W) or (B,C,H,W,D) (C is the num of landmark):return: coordination (B,C,2) or (B,C,3)"""origin_shape = heatmap.shapeheatmap = heatmap.reshape(*origin_shape[:2], -1)temp = np.argmax(heatmap, axis=-1)[..., np.newaxis]# unravel_indexout = []for dim in reversed(origin_shape[2:]):out.append(temp % dim)temp = np.floor_divide(temp, dim)out = np.concatenate(out[::-1], axis=-1)return outdef get_predict_xy(img):global model# if not os.path.exists(path):#     return Noneimg = get_img_aug(img).to(device)  # 1 * 1 * 512 * 416output = model(img)['output'].to('cpu').detach().numpy()  # 1 * 1 * 19 * 2predict_xy = get_heatmap_coordination_batch_numpy(output).squeeze(0)  # 19 * 2print(predict_xy)return predict_xydef simple_test(img):return imgif __name__ == '__main__':path = r'E:\PyCharmProject\pythonProject3\001.bmp'img = cv2.imread(path, 0)init_model('best.pth')print('finish_init')print(get_predict_xy(img).shape)print(get_predict_xy(img).dtype)

CMakeLists.txt

cmake_minimum_required(VERSION 3.24)
project(C_PLUS_PLUS VERSION 0.1.0)IF(NOT CMAKE_BUILD_TYPE)SET(CMAKE_BUILD_TYPE Release)
ENDIF()set(CMAKE_CXX_STANDARD 17)
set(PYTHON_INCLUDE_DIRS "D:/Miniconda3/envs/DL/include/")
set(NUMPY_INCLUDE_DIR "D:/Miniconda3/envs/DL/Lib/site-packages/numpy/core/include")
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_DIRS} ${NUMPY_INCLUDE_DIR})
link_directories("D:/Miniconda3/envs/DL/libs")
set(PYTHON_LIBRARIES "D:/Miniconda3/envs/DL/libs/python37.lib")
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} ${PYTHON_LIBRARIES})# Where to find CMake modules and OpenCV
# set(OpenCV_DIR "D:\\opencv-4.5.5\\opencv-4.5.5\\build")
find_package(OpenCV REQUIRED)
message(STATUS "OpenCV Include: ${OpenCV_INCLUDE_DIRS}")
message(STATUS "OpenCV LIBRARIES: ${OpenCV_LIBRARIES}")
message(STATUS "OpenCV Libs: ${OpenCV_LIBS}")INCLUDE_DIRECTORIES(${OpenCV_INCLUDE_DIRS})
target_link_libraries(${PROJECT_NAME}  ${OpenCV_LIBS})

在这里插入图片描述

相关文章:

win10 mingw 调用python

ubuntu调用pythonhttps://blog.csdn.net/qq_39942341/article/details/129333969 我这里mingw是用msys2的 opencv也是msys2装的 安装msys2和opencv可以参考这个https://blog.csdn.net/qq_39942341/article/details/129380197?spm1001.2014.3001.5502 环境变量里加入python路…...

教你使用三种方式写一个最基本的spark程序

当需要处理大规模数据并且需要进行复杂的数据处理时&#xff0c;通常会使用Hadoop生态系统中的Hive和Spark来完成任务。在下面的例子中&#xff0c;我将说明如何使用Spark编写一个程序来处理Hive中的数据&#xff0c;以满足某个特定需求。假设我们有一个Hive表&#xff0c;其中…...

软件设计师错题集

软件设计师错题集一、计算机组成与体系结构1.1 浮点数1.2 Flynn分类法1.3 指令流水线1.4 层次化存储体系1.4.1 程序的局限性1.5 Cache1.6 输入输出技术1.7 总线系统1.8 CRC循环冗余校验码二、数据结构与算法基础2.1 队列与栈2.2 树与二叉树的特殊性2.3 最优二叉树&#xff08;哈…...

【华为机试真题详解 Python实现】静态扫描最优成本【2023 Q1 | 100分】

文章目录前言题目描述输入描述输出描述示例 1输入&#xff1a;输出&#xff1a;示例 2输入&#xff1a;输出&#xff1a;题目解析参考代码前言 《华为机试真题详解》专栏含牛客网华为专栏、华为面经试题、华为OD机试真题。 如果您在准备华为的面试&#xff0c;期间有想了解的…...

算法刷题总结 (四) 动态规划

算法总结4 动态规划一、动态规划1.1、基础问题11.1.1、509. 斐波那契数列1.1.2、70. 爬楼梯1.1.3、746. 使用最小花费爬楼梯1.2、基础问题21.2.1、62. 不同路径1.2.2、63. 不同路径Ⅱ1.2.3、343. 整数拆分1.2.4、96. 不同的二叉搜索树1.3、背包问题1.3.1、01背包1.3.1.1、单次选…...

Grafana 转换数据的工具介绍

转换数据 Grafana 可以在数据显示到面板前对数据进行处理 1、点击Transform选项卡 2、选择要使用的转换类型&#xff0c;不同的转换类型配置不同 3、要新增转换类型&#xff0c;点击Add transformation 4、使用右上角调式按钮可以调式转换 支持的转换类型&#xff1a; Add f…...

Linux 学习笔记

一、 概述 1. 操作系统 ① 计算机由硬件和软件组成 ② 操作系统属于软件范畴&#xff0c;主要作用是协助用户调度硬件工作&#xff0c;充当用户和计算机硬件之间的桥梁 ③ 常见的操作系统 &#x1f920; PC端&#xff1a;Windows、Linux、MacOS&#x1f920; 移动端&#…...

HTML注入专精整理

目录 HTML注入介绍 抽象解释 HTML注入的影响 HTML注入与XSS的区别 HTML元素流程图...

看完这篇我不信你不会二叉树的层序遍历【C语言】

目录 实现思路 代码实现 之前介绍了二叉树的前、中、后序三种遍历&#xff0c;采用的是递归的方式。今天我们来学习另外一种遍历方式——层序遍历。层序遍历不容小觑&#xff0c;虽然实现方法并不难&#xff0c;但是它所采取的思路是很值得学习的&#xff0c;与前三者不同&am…...

案例17-环境混用带来的影响

目录一、背景介绍背景事故二、思路&方案三、过程四、总结nginx做转发fastdfs&#xff08;文件上传下载&#xff09;五、升华一、背景介绍 本篇博客主要介绍开发中项目使用依赖项环境闭一只带来的恶劣影响&#xff0c;在错误中成长进步。 背景 本公司另外一个产品开发God…...

知识蒸馏论文阅读:DKD算法笔记

标题&#xff1a;Decoupled Knowledge Distillation 会议&#xff1a;CVPR2022 论文地址&#xff1a;https://ieeexplore.ieee.org/document/9879819/ 官方代码&#xff1a;https://github.com/megvii-research/mdistiller 作者单位&#xff1a;旷视科技、早稻田大学、清华大学…...

Sentinel架构篇 - 熔断降级

熔断降级 概念 除了流量控制以外&#xff0c;对调用链路中不稳定的资源进行熔断降级也是保障高可用的重要措施之一。一个服务常常会调用其它模块&#xff0c;可能是一个远程服务、数据库、或者第三方 API 等。然而&#xff0c;被依赖的服务的稳定性是不能保证的。如果依赖的服…...

shell脚本的一些记录 与jenkins的介绍

shell 脚本的执行 sh ***.sh shell脚本里面的命令 其实就是终端执行一些命令 shell 连接服务器 可以直接ssh连接 但是这样最好是无密码的 不然后面的命令就不好写了 换而言之有密码得 不好写脚本 需要下载一些expect的插件之类的才可以 判断语句 的示例 需要注意的是…...

JVM的了解与学习

一:jvm是什么 jvm是java虚拟机java Virtual Machine的缩写 jdk包含jre和java DevelopmentTools 二:什么是java虚拟机 虚拟机是一种抽象化的计算机,通过在实际的计算机上仿真模拟各种计算机功能来实现的。java虚拟机有自己完善的硬体结构,如处理器、堆栈、寄存器等,还有…...

提升数字品牌的5个技巧

“品牌”或“品牌推广”的概念通常用于营销。因为建立您的企业品牌对于产品来说极其重要&#xff0c;品牌代表了您与客户互动的身份和声音。今天&#xff0c;让我们来看看在数字领域提升品牌的一些有用的技巧。如何在数字领域提升您的品牌&#xff1f;在了解这些技巧之前&#…...

java通过反射获取加了某个注解的所有的类

有时候我们会碰到这样的情况&#xff1a;有n个场景&#xff0c;每个场景都有自己的逻辑&#xff0c;即n个处理逻辑&#xff0c;这时候我们就需要通过某个参数的值代表这n个场景&#xff0c;然后去加载每个场景不同的bean对象&#xff0c;即不同的类&#xff0c;这些类中都有一个…...

Warshall算法

&#x1f680;write in front&#x1f680; &#x1f4dc;所属专栏&#xff1a;> 算法 &#x1f6f0;️博客主页&#xff1a;睿睿的博客主页 &#x1f6f0;️代码仓库&#xff1a;&#x1f389;VS2022_C语言仓库 &#x1f3a1;您的点赞、关注、收藏、评论&#xff0c;是对我…...

vector中迭代器失效的问题及解决办法

目录 vector常用接口 vector 迭代器失效问题 vector中深浅拷贝问题 vector的数据安排以及操作方式&#xff0c;与array非常相似。两者的唯一差别在于空间的运用的灵活性。array 是静态空间&#xff0c;一旦配置了就不能改变&#xff1b;要换个大(或小) 一点的房子&#x…...

【蓝桥杯刷题训练营】day05

1 数的分解 拆分成3个数相加得到该数 然后采用了一种巨愚蠢的办法&#xff1a; int main() {int count 0;int a 2;int b 0;int c 1;int d 9;int a1, a2, a3;int c1, c2, c3;int d1, d2, d3;for (a1 0; a1 < 2; a1){for (a2 0; a2 < 2; a2){for (a3 0; a3 <…...

线程中断interrupt导致sleep产生的InterruptedException异常

强制当前正在执行的线程休眠&#xff08;暂停执行&#xff09;&#xff0c;以“减慢线程”。 Thread.sleep(long millis)和Thread.sleep(long millis, int nanos)静态方法当线程睡眠时&#xff0c;它睡在某个地方&#xff0c;在苏醒之前不会返回到可运行状态。 当睡眠时间到期…...

ubuntu的快速安装与配置

文章目录前言一、快速安装二 、基础配置1 Sudo免密码2 ubuntu20.04 pip更新源3 安装和配置oneapi(infort/mpi/mkl) apt下载第一次下载的要建立apt源apt下载&#xff08;infort/mpi/mkl)4 安装一些依赖库等5 卸载WSLpython总结前言 win11系统 ubuntu20.04 提示&#xff1a;以下…...

人工智能AI工具汇总(AIGC ChatGPT时代个体崛起)

NameCategoryWebsiteDescription描述《AIGC时代&#xff1a;超级个体的崛起》小报童https://xiaobot.net/p/SuperIndividual 介绍AIGC&#xff0c;ChatGPT&#xff0c;使用技巧与搞钱方式。Masterpiece Studio3Dhttps://masterpiecestudio.comSimplifying 3D Creation with AI…...

【rust-grpc-proxy】在k8s中,自动注入代理到pod中,再不必为grpc调试而烦恼

目录前言原理sidecarwebhook实现安装k8s设置webhook使用尾语前言 rust-grpc-proxy 目前功能基本完善。是时候上环境开始应用了。 之前考虑是gateway模式或者sidecar模式。 思考良久之后&#xff0c;觉得两种模式都有使用场景&#xff0c;那就都支持。本次就带来sidecar模式的食…...

VisualStudio2022制作多项目模板及Vsix插件

一、安装工作负载 在vs2022上安装“visual studio扩展开发 ”工作负载 二、制作多项目模板 导出项目模板这个我就不再多说了&#xff08;项目→导出模板→选择项目模板&#xff0c;选择要导出的项目→填写模板信息→完成&#xff09;。 1.准备模板文件 将解决方案中的多个…...

仿写简单IOC

目录 TestController类: UserService类: 核心代码SpringIOC&#xff1a; Autowired和Component注解 SpringIOCTest 类 ​编辑 总结&#xff1a; TestController类: Component public class TestController {Autowiredprivate UserService userService;public void test…...

liunx下安装node exporter

1 建立文件夹 cd /opt mkdir software 下载最新的包&#xff0c;并解压 https://prometheus.io/download/ 下载 curl -LO https://github.com/prometheus/node_exporter/releases/download/v0.18.1/node_exporter-0.18.1.linux-amd64.tar.gz 3.解压 tar -xvf node_exporter-0.…...

lambda函数

Lambda(函数指针)lambda 是c11非常重要也是最常用的特性之一&#xff0c;他有以下优点&#xff1a;可以就地匿名定义目标函数或函数对象&#xff0c;不需要额外写一个函数lambda表达式是一个匿名的内联函数lambda表达式定义了一个匿名函数&#xff0c;语法如下&#xff1a;[cap…...

【Python入门第二十七天】Python 日期

Python 日期 Python 中的日期不是其自身的数据类型&#xff0c;但是我们可以导入名为 datetime 的模块&#xff0c;把日期视作日期对象进行处理。 实例 导入 datetime 模块并显示当前日期&#xff1a; import datetimex datetime.datetime.now() print(x)运行实例 2023-0…...

C++基础知识【5】数组和指针

目录 一、概述 数组 指针 二、数组 2.1、数组的声明 2.2、数组的初始化 2.3、数组的访问 2.4、多维数组 2.5、数组作为函数参数 三、指针 3.1、指针的声明 3.2、指针的赋值 3.3、指针的访问 3.4、指针运算 3.5、指针数组和数组指针 3.6、二级指针 四、数组和指…...

Vim使用操作命令笔记

Vim使用操作命令笔记在普通模式下&#xff0c;输入 : help tutor 就可以进入vim的教学       在 terminal 中输入 vim 文件名 就可以打开文件    vim有两种模式   normal mode &#xff08;普通模式&#xff09;→ 指令操作   insert mode &#xff08;输入模式&…...