当前位置: 首页 > 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;在苏醒之前不会返回到可运行状态。 当睡眠时间到期…...

Leetcode 3576. Transform Array to All Equal Elements

Leetcode 3576. Transform Array to All Equal Elements 1. 解题思路2. 代码实现 题目链接&#xff1a;3576. Transform Array to All Equal Elements 1. 解题思路 这一题思路上就是分别考察一下是否能将其转化为全1或者全-1数组即可。 至于每一种情况是否可以达到&#xf…...

golang循环变量捕获问题​​

在 Go 语言中&#xff0c;当在循环中启动协程&#xff08;goroutine&#xff09;时&#xff0c;如果在协程闭包中直接引用循环变量&#xff0c;可能会遇到一个常见的陷阱 - ​​循环变量捕获问题​​。让我详细解释一下&#xff1a; 问题背景 看这个代码片段&#xff1a; fo…...

AspectJ 在 Android 中的完整使用指南

一、环境配置&#xff08;Gradle 7.0 适配&#xff09; 1. 项目级 build.gradle // 注意&#xff1a;沪江插件已停更&#xff0c;推荐官方兼容方案 buildscript {dependencies {classpath org.aspectj:aspectjtools:1.9.9.1 // AspectJ 工具} } 2. 模块级 build.gradle plu…...

sipsak:SIP瑞士军刀!全参数详细教程!Kali Linux教程!

简介 sipsak 是一个面向会话初始协议 (SIP) 应用程序开发人员和管理员的小型命令行工具。它可以用于对 SIP 应用程序和设备进行一些简单的测试。 sipsak 是一款 SIP 压力和诊断实用程序。它通过 sip-uri 向服务器发送 SIP 请求&#xff0c;并检查收到的响应。它以以下模式之一…...

PostgreSQL——环境搭建

一、Linux # 安装 PostgreSQL 15 仓库 sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-$(rpm -E %{rhel})-x86_64/pgdg-redhat-repo-latest.noarch.rpm# 安装之前先确认是否已经存在PostgreSQL rpm -qa | grep postgres# 如果存在&#xff0…...

CVPR2025重磅突破:AnomalyAny框架实现单样本生成逼真异常数据,破解视觉检测瓶颈!

本文介绍了一种名为AnomalyAny的创新框架&#xff0c;该方法利用Stable Diffusion的强大生成能力&#xff0c;仅需单个正常样本和文本描述&#xff0c;即可生成逼真且多样化的异常样本&#xff0c;有效解决了视觉异常检测中异常样本稀缺的难题&#xff0c;为工业质检、医疗影像…...

VisualXML全新升级 | 新增数据库编辑功能

VisualXML是一个功能强大的网络总线设计工具&#xff0c;专注于简化汽车电子系统中复杂的网络数据设计操作。它支持多种主流总线网络格式的数据编辑&#xff08;如DBC、LDF、ARXML、HEX等&#xff09;&#xff0c;并能够基于Excel表格的方式生成和转换多种数据库文件。由此&…...

云安全与网络安全:核心区别与协同作用解析

在数字化转型的浪潮中&#xff0c;云安全与网络安全作为信息安全的两大支柱&#xff0c;常被混淆但本质不同。本文将从概念、责任分工、技术手段、威胁类型等维度深入解析两者的差异&#xff0c;并探讨它们的协同作用。 一、核心区别 定义与范围 网络安全&#xff1a;聚焦于保…...

Vue3中的computer和watch

computed的写法 在页面中 <div>{{ calcNumber }}</div>script中 写法1 常用 import { computed, ref } from vue; let price ref(100);const priceAdd () > { //函数方法 price 1price.value ; }//计算属性 let calcNumber computed(() > {return ${p…...

【iOS】 Block再学习

iOS Block再学习 文章目录 iOS Block再学习前言Block的三种类型__ NSGlobalBlock____ NSMallocBlock____ NSStackBlock__小结 Block底层分析Block的结构捕获自由变量捕获全局(静态)变量捕获静态变量__block修饰符forwarding指针 Block的copy时机block作为函数返回值将block赋给…...