C++调用python模块

vs配置
这里写图片描述
1.配置文件包含目录为

C:\Users\Administrator\AppData\Local\Programs\Python\Python35\include

2.库目录为

C:\Users\Administrator\AppData\Local\Programs\Python\Python35\libs

3.linker->input为

python35.lib

4.C++调用代码部分

#include <python.h>
#include <iostream>

using namespace std;

int main()
{
	const char* picpath = "E:/Image/01.jpg";
	const char* tempath = "E:/Image/04.jpg";
	Py_Initialize();
	if (!Py_IsInitialized()){
		return -1;
	}
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('./')");
	PyObject* pMod = NULL;
	PyObject* pFunc = NULL;
	PyObject* pParm = NULL;
	PyObject* pRetVal = NULL;
	int iRetVal = -999;
	const char* modulName = "Insert";    //这个是被调用的py文件模块名字
	pMod = PyImport_ImportModule(modulName);
	if (!pMod)
	{
		return -1;
	}
	const char* funcName = "matchAB3";  //这是此py文件模块中被调用的函数名字
	pFunc = PyObject_GetAttrString(pMod, funcName);
	if (!pFunc)
	{
		return -2;
	}
	pParm = PyTuple_New(5);//创建传参个数
	PyTuple_SetItem(pParm, 0, Py_BuildValue("s", picpath));//传入的参数,是图片的路径
	PyTuple_SetItem(pParm, 1, Py_BuildValue("s", tempath));//传入的参数,是图片的路径
	PyTuple_SetItem(pParm, 2, Py_BuildValue("i", 150));//传入int的参数
	PyTuple_SetItem(pParm, 3, Py_BuildValue("f", 0.5));//传入float的参数
	PyTuple_SetItem(pParm, 4, Py_BuildValue("i", 1000));//传入int的参数
	pRetVal = PyEval_CallObject(pFunc, pParm);//这里开始执行py脚本
	PyArg_Parse(pRetVal, "i", &iRetVal);//py脚本返回值给iRetVal
										//PyErr_Print();
	std::cout << iRetVal;
	return iRetVal;
}

5.python模块部分

import cv2
import matplotlib.pyplot as plt
import numpy as np
import time
from skimage.measure import compare_ssim
import imutils
import scipy
import argparse

def matchAB3(fileA, fileB, SPACE, THRESHOLD, AREARECT):
    m=7
    start = time.clock()
    # 窗口的边长
    window_size = 150
    # 读取图像数据
    imgA = cv2.imread(fileA)
    imgB = cv2.imread(fileB)
    # imgA = cv2.resize(imgA, (1400, 1000))
    # imgB = cv2.resize(imgB, (1400, 1000))
    # 转换成灰色
    grayA = cv2.cvtColor(imgA, cv2.COLOR_BGR2GRAY)
    grayB = cv2.cvtColor(imgB, cv2.COLOR_BGR2GRAY)

    # 获取图片A的大小
    height, width = grayA.shape
   # print(height, width)
    # 取局部图像,寻找匹配位置
    result_window = np.zeros((height, width), dtype=imgA.dtype)
    for start_y in range(25, height - window_size - 25, SPACE):  # 处理的密度
        for start_x in range(25, width - window_size - 25, SPACE):
            window = grayA[start_y:start_y + window_size, start_x:start_x + window_size]  # 100*100的窗口
            grayC = grayB[start_y - 25:start_y + window_size + 25, start_x - 25:start_x + window_size + 25]
            match = cv2.matchTemplate(grayC, window, cv2.TM_CCOEFF_NORMED)  # 窗口内容和graB进行图像匹配
            _, _, _, max_loc = cv2.minMaxLoc(match)  # 返回最大匹配的位置
            matched_window = grayC[max_loc[1]:max_loc[1] + window_size, max_loc[0]:max_loc[0] + window_size]
            # result = cv2.absdiff(window, matched_window)  # 两个窗口的差值
            # cv2.imwrite("E:/Image/absdiff.png",result)
            (score, diff) = compare_ssim(window, matched_window, full=True)

            if (score <= THRESHOLD):
                diff = (diff * 255).astype("uint8")
        #        print("{}".format(score))
                result_window[start_y:start_y + window_size, start_x:start_x + window_size] = diff
            '''
            diff = (diff * 255).astype("uint8")
            print("{}".format(score))
            result_window[start_y:start_y + window_size, start_x:start_x + window_size] = diff
            '''
            # print("running...")
    imgC = imgA.copy()
    imgD = imgB.copy()
    thresh = cv2.threshold(result_window, 125, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if imutils.is_cv2() else cnts[1]
    for c in cnts:
        (x, y, w, h) = cv2.boundingRect(c)
        if (w * h >= AREARECT):
            cv2.rectangle(imgC, (x, y), (x + w, y + h), (255, 0, 0), 2)
            cv2.rectangle(imgD, (x, y), (x + w, y + h), (0, 0, 255), 2)
    # result_window_bin = cv2.adaptiveThreshold(result_window, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 4)
    # _, contours, _ = cv2.findContours(result_window_bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    # imgC = imgA.copy()
    # imgD = imgB.copy()
    # for contour in contours:
    #     min = np.nanmin(contour, 0)
    #     max = np.nanmax(contour, 0)
    #     loc1 = (min[0][0], min[0][1])
    #     loc2 = (max[0][0], max[0][1])
    #     cv2.rectangle(imgC, loc1, loc2, (255,0,0), 1)
    #     cv2.rectangle(imgD, loc1, loc2, (0,255,0), 1)
    end = time.clock()
  #  print('totally time:', end - start)
    sPath = str(SPACE) + "," + str(THRESHOLD) + "," + str(AREARECT)
    sPath = "E:/Image/" + sPath + "_"
    cv2.imwrite(sPath + "pic.png", cv2.cvtColor(imgC, cv2.COLOR_BGR2RGB))
    cv2.imwrite(sPath + "picCompared.png", cv2.cvtColor(imgD, cv2.COLOR_BGR2RGB))
    return m

重要补充
遇到C++调用py文件向py文件传输含有中文的参数时需要在C++代码中加入(VS编码是unicode Python的编码是utf8会有编码不一致问题)

#pragma execution_character_set("utf-8")

参考文献:https://blog.csdn.net/qq_34484472/article/details/76598852
传参的参考文献:https://blog.csdn.net/vampirem/article/details/12948955

方法可以根据自己的需求来改。

评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值