Qt Creator 通过python解释器调用*.py

news2024/10/11 5:51:30

全是看了大佬们的帖子,结合chatGPT才揉出来。在此做个记录。

  1. 安装python
  2. 在Qt Creator *.pro 文件中配置好环境
  3. 来个简单的example.py
  4. 调用代码
  5. 安装pip
  6. 添加opencv等库
  7. 调用包含了opencv库的py代码
  8. 成功

*.pro配置:

INCLUDEPATH += C:\Users\xuanm\AppData\Local\Programs\Python\Python312\include
LIBS      += -LC:\Users\xuanm\AppData\Local\Programs\Python\Python312\libs  -lpython312

example.py源码:

# example.py
def add(a, b):
    return a + b

Qt Creator里面调用example.py的C++函数:


int MainWindow::testPy()
{
    const wchar_t * pythonHome = L"C:/Users/xuanm/AppData/Local/Programs/Python/Python312";
    Py_SetPythonHome(pythonHome);

   // 初始化 Python 解释器
    Py_Initialize();

    // 添加目录到 Python 模块搜索路径
    PyObject* sysPath = PySys_GetObject("path");
    PyObject* pPath = PyUnicode_FromString("C:/temp");
    PyList_Append(sysPath, pPath);
    Py_DECREF(pPath);  // 释放引用
    // 导入 Python 脚本
    PyObject* pModule = PyImport_ImportModule("example");
    if (!pModule) {
        PyErr_Print();
        std::cerr << "Failed to load module." << std::endl;
        return 1;
    }

    // 获取函数对象
    PyObject* pFunc = PyObject_GetAttrString(pModule, "add");
    if (!pFunc || !PyCallable_Check(pFunc)) {
        PyErr_Print();
        std::cerr << "Failed to get function." << std::endl;
        return 1;
    }

    // 准备参数
    PyObject* pArgs = PyTuple_Pack(2, PyLong_FromLong(5), PyLong_FromLong(3));

    // 调用函数
    PyObject* pValue = PyObject_CallObject(pFunc, pArgs);
    if (pValue) {
        // 打印结果
        std::cout << "Result: " << PyLong_AsLong(pValue) << std::endl;
        Py_DECREF(pValue);
    } else {
        PyErr_Print();
        std::cerr << "Function call failed." << std::endl;
    }

    // 清理
    Py_XDECREF(pFunc);
    Py_XDECREF(pModule);
    Py_XDECREF(pArgs);

    // 结束 Python 解释器
    Py_Finalize();
}

含opencv库的*.py:

#-*- coding: utf-8 -*-

import os.path
import copy
import cv2
import numpy as np


# 椒盐噪声
def SaltAndPepper(src, percetage):
    SP_NoiseImg = src.copy()
    SP_NoiseNum = int(percetage * src.shape[0] * src.shape[1])
    for i in range(SP_NoiseNum):
        randR = np.random.randint(0, src.shape[0] - 1)
        randG = np.random.randint(0, src.shape[1] - 1)
        randB = np.random.randint(0, 3)
        if np.random.randint(0, 1) == 0:
            SP_NoiseImg[randR, randG, randB] = 0
        else:
            SP_NoiseImg[randR, randG, randB] = 255
    return SP_NoiseImg


# 高斯噪声
def addGaussianNoise(image, percetage):
    G_Noiseimg = image.copy()
    w = image.shape[1]
    h = image.shape[0]
    G_NoiseNum = int(percetage * image.shape[0] * image.shape[1])
    for i in range(G_NoiseNum):
        temp_x = np.random.randint(0, h)
        temp_y = np.random.randint(0, w)
        G_Noiseimg[temp_x][temp_y][np.random.randint(3)] = np.random.randn(1)[0]
    return G_Noiseimg


# 昏暗
def darker(image, percetage=0.9):
    image_copy = image.copy()
    w = image.shape[1]
    h = image.shape[0]
    # get darker
    for xi in range(0, w):
        for xj in range(0, h):
            image_copy[xj, xi, 0] = int(image[xj, xi, 0] * percetage)
            image_copy[xj, xi, 1] = int(image[xj, xi, 1] * percetage)
            image_copy[xj, xi, 2] = int(image[xj, xi, 2] * percetage)
    return image_copy


# 亮度
def brighter(image, percetage=1.5):
    image_copy = image.copy()
    w = image.shape[1]
    h = image.shape[0]
    # get brighter
    for xi in range(0, w):
        for xj in range(0, h):
            image_copy[xj, xi, 0] = np.clip(int(image[xj, xi, 0] * percetage), a_max=255, a_min=0)
            image_copy[xj, xi, 1] = np.clip(int(image[xj, xi, 1] * percetage), a_max=255, a_min=0)
            image_copy[xj, xi, 2] = np.clip(int(image[xj, xi, 2] * percetage), a_max=255, a_min=0)
    return image_copy


# 旋转
def rotate(image, angle, center=None, scale=1.0):
    (h, w) = image.shape[:2]
    # If no rotation center is specified, the center of the image is set as the rotation center
    if center is None:
        center = (w / 2, h / 2)
    m = cv2.getRotationMatrix2D(center, angle, scale)
    rotated = cv2.warpAffine(image, m, (w, h))
    return rotated


# 翻转
def flip(image):
    flipped_image = np.fliplr(image)
    return flipped_image


def work(file_dir):
# 图片文件夹路径
    for img_name in os.listdir(file_dir):
        img_path = file_dir + '\\' + img_name
        img = cv2.imread(img_path)
        # cv2.imshow("1",img)
        # cv2.waitKey(5000)
        # 旋转
        rotated_90 = rotate(img, 90)
        cv2.imwrite(file_dir +'\\'+ img_name[0:-4] + '_r90.jpg', rotated_90)
        # rotated_180 = rotate(img, 180)
        # cv2.imwrite(file_dir +'\\'+ img_name[0:-4] + '_r180.jpg', rotated_180)

    # for img_name in os.listdir(file_dir):
    #     img_path = file_dir + img_name
    #     img = cv2.imread(img_path)
    #     镜像
    #     flipped_img = flip(img)
    #     cv2.imwrite(file_dir +'\\' + img_name[0:-4] + '_fli.jpg', flipped_img)
        #
        # # 增加噪声
       # img_salt = SaltAndPepper(img, 0.3)
     #   cv2.imwrite(file_dir + '\\' + img_name[0:-4] + '_salt.jpg', img_salt)
      #  img_gauss = addGaussianNoise(img, 0.3)
      #  cv2.imwrite(file_dir +'\\' +  img_name[0:-4] + '_noise.jpg', img_gauss)
    #
    # # 变亮、变暗
    # img_darker = darker(img)
    # cv2.imwrite(file_dir +'\\' + img_name[0:-4] + '_darker.jpg', img_darker)
    # img_brighter = brighter(img)
    # cv2.imwrite(file_dir + '\\' + img_name[0:-4] + '_brighter.jpg', img_brighter)
    #
    # blur = cv2.GaussianBlur(img, (7, 7), 1.5)
    # #      cv2.GaussianBlur(图像,卷积核,标准差)
    # cv2.imwrite(file_dir + img_name[0:-4] + '_blur.jpg', blur)

调用含opencv库的*.py C++函数:


int MainWindow::testYBZQ()
{
   const wchar_t * pythonHome = L"C:/Users/xuanm/AppData/Local/Programs/Python/Python312";
    Py_SetPythonHome(pythonHome);

  // 初始化 Python 解释器
    Py_Initialize();

    // 添加目录到 Python 模块搜索路径
    PyObject* sysPath = PySys_GetObject("path");

    PyObject* pPath = PyUnicode_FromString("C:/temp");
    PyList_Append(sysPath, pPath);
    Py_DECREF(pPath);  // 释放引用

    // 添加标准库路径
    PyObject* stdLibPath = PyUnicode_FromString("C:/Users/xuanm/AppData/Local/Programs/Python/Python312/libs");
    PyList_Append(sysPath, stdLibPath);
    Py_DECREF(stdLibPath);

    // 添加 site-packages 路径
    PyObject* sitePackagesPath = PyUnicode_FromString("C:/Users/xuanm/AppData/Local/Programs/Python/Python312/Lib/site-packages");
    PyList_Append(sysPath, sitePackagesPath);
    Py_DECREF(sitePackagesPath);


    // 导入 Python 脚本
    PyObject* pModule = PyImport_ImportModule("data_augmentation");
    if (!pModule) {
        PyErr_Print();
        std::cerr << "Failed to load module." << std::endl;
        return 1;
    }

    // 获取函数对象
    PyObject* pFunc = PyObject_GetAttrString(pModule, "work");
    if (!pFunc || !PyCallable_Check(pFunc)) {
        PyErr_Print();
        std::cerr << "Failed to get function." << std::endl;
        return 1;
    }

    // 准备参数

    std::string strParam = "C:/temp/sar_sample";
    PyObject* pStrParam = PyUnicode_FromString(strParam.c_str());

    PyObject* pArgs = PyTuple_Pack(1, pStrParam);

    // 调用函数
    PyObject* pValue = PyObject_CallObject(pFunc, pArgs);
    if (pValue) {
        // 打印结果
        std::cout << "Result: " << PyLong_AsLong(pValue) << std::endl;
        Py_DECREF(pValue);
    } else {
        PyErr_Print();
        std::cerr << "Function call failed." << std::endl;
    }

    // 清理
    Py_XDECREF(pFunc);
    Py_XDECREF(pModule);
    Py_XDECREF(pArgs);

    // 结束 Python 解释器
    Py_Finalize();
}

程序运行出了正确结果,报错:

Result: -1
TypeError: 'NoneType' object cannot be interpreted as an integer

再次感谢各位大佬的帖子,谢谢。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2204307.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

接口测试-day3-jmeter-2组件和元件

组件和元件&#xff1a; 组件&#xff1a;组件指的是jmeter里面任意一个可以使用的功能。比如说查看结果树或者是http请求 元件&#xff1a;元件指是提对组件的分类 组件的作用域&#xff1a;组件放的位置不一样生效也不一样。 作用域取决于组件的的层级结构并不取决于组件的…

论文阅读:OpenSTL: A Comprehensive Benchmark of Spatio-Temporal Predictive Learning

论文地址&#xff1a;arxiv 摘要 由于时空预测没有标准化的比较&#xff0c;所以为了解决这个问题&#xff0c;作者提出了 OpenSTL&#xff0c;这是一个全面的时空预测学习基准。它将流行的方法分为基于循环和非循环模型两类。OpenSTL提供了一个模块化且可扩展的框架&#xff…

算法: 前缀和题目练习

文章目录 前缀和题目练习前缀和二维前缀和寻找数组的中心下标除自身以外数组的乘积和为 K 的子数组和可被 K 整除的子数组连续数组矩阵区域和 前缀和题目练习 前缀和 自己写出来了~ 坑: 数据太大,要用long. import java.util.Scanner;public class Main {public static voi…

“国货户外TOP1”凯乐石签约实在智能,RPA助力全域电商运营自动化提效

近日&#xff0c;国货第一户外品牌KAILAS凯乐石与实在智能携手合作&#xff0c;基于实在智能“取数宝”自动化能力&#xff0c;打通运营数据获取全链路&#xff0c;全面提升淘宝、天猫、抖音等平台的运营效率与消费者体验&#xff0c;以自动化能力驱动企业增长。 KAILAS凯乐石…

雨晨 24H2 正式版 Windows 11 iot ltsc 2024 适度 26100.2033 VIP2IN1

雨晨 24H2 正式版 Windows 11 iot ltsc 2024 适度 26100.2033 VIP2IN1 install.wim 索引: 1 名称: Windows 11 IoT 企业版 LTSC 2024 x64 适度 (生产力环境推荐) 描述: Windows 11 IoT 企业版 LTSC 2024 x64 适度 By YCDISM 2024-10-09 大小: 15,699,006,618 个字节 索引: 2 …

Jenkins常见问题处理

Jenkins操作手册 读者对象&#xff1a;生产环境管理及运维人员 Jenkins作用&#xff1a;项目自动化构建部署。 一、登陆 二、新增用户及设置权限 2.1&#xff1a;新增用户 点击Manager Jenkins → Manager Users → Create User 2.2&#xff1a;权限 点击Manager Jenkins…

互联网线上融合上门洗衣洗鞋小程序,让洗衣洗鞋像点外卖一样简单

随着服务创新的风潮&#xff0c;众多商家已巧妙融入预约上门洗鞋新风尚&#xff0c;并携手洗鞋小程序&#xff0c;开辟线上蓝海。那么&#xff0c;这不仅仅是一个小程序&#xff0c;它究竟蕴含着哪些诱人好处呢&#xff1f; 1. 无缝融合&#xff0c;双线共赢&#xff1a;小程序…

Corel VideoStudio Ultimate 会声会影2025旗舰版震憾来袭,会声会影2025旗舰版最低系统要求

软件介绍 会声会影2025旗舰版全名&#xff1a;Corel VideoStudio Ultimate 2025&#xff0c;相信做视频剪辑的朋友都认识它&#xff0c;会声会影是一款强大的视频剪辑编辑软件&#xff0c;运用数百种拖放滤镜、效果、图形、标题和过渡&#xff0c;探索新奇好玩的新增面部追踪贴…

彩族相机内存卡恢复多种攻略:告别数据丢失

在数字时代&#xff0c;相机内存卡作为我们存储珍贵照片和视频的重要媒介&#xff0c;其数据安全性显得尤为重要。然而&#xff0c;意外删除、错误格式化、存储卡损坏等情况时有发生&#xff0c;导致数据丢失&#xff0c;给用户带来不小的困扰。本文将详细介绍彩族相机内存卡数…

【万字长文】Word2Vec计算详解(三)分层Softmax与负采样

【万字长文】Word2Vec计算详解&#xff08;三&#xff09;分层Softmax与负采样 写在前面 第三部分介绍Word2Vec模型的两种优化方案。 【万字长文】Word2Vec计算详解&#xff08;一&#xff09;CBOW模型 markdown行 9000 【万字长文】Word2Vec计算详解&#xff08;二&#xff0…

初级网络工程师之从入门到入狱(五)

本文是我在学习过程中记录学习的点点滴滴&#xff0c;目的是为了学完之后巩固一下顺便也和大家分享一下&#xff0c;日后忘记了也可以方便快速的复习。 网络工程师从入门到入狱 前言一、链路聚合1.1、手动进行链路聚合1.1.1、 拓扑图&#xff1a;1.1.2、 LSW11.1.3、 LSW2 1.2、…

5.C语言基础入门:数据类型、变量声明与创建详解

C语言基础入门&#xff1a;数据类型、变量声明与创建详解 C语言往期系列文章目录 往期回顾&#xff1a; C语言是什么&#xff1f;编程界的‘常青树’&#xff0c;它的辉煌你不可不知VS 2022 社区版C语言的安装教程&#xff0c;不要再卡在下载0B/s啦C语言入门&#xff1a;解锁…

Elasticsearch 索引数据预处理

pipeline 在文档写入 ES 之前&#xff0c;对数据进行预处理&#xff08;ingest&#xff09;工作通过定义 pipeline 和 processors 实现。 注意&#xff1a;数据预处理必须在 Ingest node 节点处理&#xff0c;ES 默认所有节点都是 Ingest node。 如果需要禁用 Ingest &#x…

Java中的拦截器、过滤器及监听器

过滤器&#xff08;Filter&#xff09;监听器&#xff08;Listener&#xff09;拦截器&#xff08;Interceptor&#xff09;关注点web请求系统级别参数、对象Action&#xff08;部分web请求&#xff09;如何实现函数回调事件Java反射机制&#xff08;动态代理&#xff09;应用场…

《大道平渊》· 廿贰 —— 杀心篇:独立人格的形成

《大道平渊》 独立人格的形成&#xff0c;在杀心的过程中会越来越完备。 在这个漫长的过程中&#xff0c;你会一次次击碎自己固有的三观&#xff0c;慢慢再修复你的三观。 . 不要认为一个人的明白&#xff0c;都是恍然大悟&#xff0c;都是碰到了高人指点。 并不是这样的&a…

使用 Raspberry Pi Pico W 的基于 MQTT 的分布式网络自适应估计

英文论文标题&#xff1a;MQTT based Adaptive Estimation over Distributed Network using Raspberry Pi Pico W 中文论文标题&#xff1a;使用 Raspberry Pi Pico W 的基于 MQTT 的分布式网络自适应估计 作者信息&#xff1a; Prantaneel DebnathAnshul GusainParth Sharm…

46 C 语言文件的打开与关闭、写入与读取函数:fopen、fclose、fputc、fputs、fprintf、fgetc、fgets、fscanf

目录 1 文件的存储形式 2 打开文件——fopen() 函数 2.1 功能描述 2.2 函数原型 2.3 文件打开方式&#xff08;模式&#xff09; 3 关闭文件——fclose() 函数 3.1 功能描述 3.2 函数原型 4 常见的文件写入方式 4.1 fputc() 函数 4.1.1 功能描述 4.1.2 函数原型 4…

第四范式发布全新一代文档数字化管理平台Smart Archive 2.0

产品上新 Product Release 今日&#xff0c;第四范式正式推出全新一代文档数字化管理平台——Smart Archive 2.0。该产品基于第四范式自研的文档处理大模型&#xff0c;实现零样本下对企业文档的精准识别及信息提取。文档处理大模型利用二十多个行业&#xff0c;上百种场景下的…

【华为】默认路由配置

1.配置接入层&#xff1a; LSW1&#xff08;LSW3同理&#xff09;: vlan batch 10 20 in g0/0/1 port link-type ac port default vlan 10 in g0/0/2 port link-type ac port default vlan 20 in g0/0/24 port link-type tr port tr allow-pass vlan 10 20 2.配置汇聚层&#x…

Spring Boot 集成 LiteFlow 实现业务流程编排

LiteFlow 是一款轻量级的流程编排框架,它允许开发者通过简单的配置方式,将复杂的业务流程分解为多个独立的节点,然后通过定义规则来编排节点,达到解耦业务逻辑、提高代码可维护性的目的 1. LiteFlow 的基本概念 在 LiteFlow 中,主要有以下几个概念: 节点 (Node):代表一…