欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++读取图片发送给python显示出来

程序员文章站 2024-01-19 14:03:34
...

代码是在C++中用opencv 读取图片,然后讲图片转化为numpy 的数组形式发送给python read_img.py文件。最后我们在python文件里面接收到这个numpy 数组,然后通过PIL库读取并且显示你的图片
这里需要提醒的是 python 里面最好不要用 python-opencv显示,不然会出现错误,可能的原因是因为C++和python都用了opencv.使用PIL读取图片,便不会存在这样的问题。 之后,你便可以用python 训练的神经网络去使用或者预测图片了。

C++代码 :

#include <iostream>
#include <stdlib.h>
#include <python2.7/Python.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <numpy/arrayobject.h>
#include <opencv2/imgproc.hpp>
#include <memory>
using namespace std;
using namespace cv;
int main()
{

    Py_Initialize();

    std::cout << "Importing Deeplab V3 ..." << std::endl;


    PyRun_SimpleString("import sys,os");
    PyRun_SimpleString("sys.path.append('../python/')");
    PyObject *py_module =NULL,*pFunc=NULL;


    // 导入deeplab.py  module
    // 2021.03.05 发现 matplotlib.pyplot 导入会出错  
    py_module = PyImport_ImportModule("read_image");    //导入read_image.py文件
    if (!py_module)
    {

        cout << "Python get module failed." << endl;
        return 0;
    }
    else
        cout << "Python get module succeed!" << endl;


    //   C++ 代码 读取图片传送给 python
  Mat img = imread("./test.png",CV_LOAD_IMAGE_COLOR);
    int m, n;
    n = img.cols *3;
    m = img.rows;

    unsigned char *data = new unsigned char[m*n];
    int p = 0;
    for (int i = 0; i < m; ++i)
    {
        for (int j = 0; j < n ; ++j)
        {
            data[p] = img.at<unsigned char>(i,j);
            p++;
        }
    }

    import_array();     //特别提醒:必须有传数组时需要.需要修改代码,不然会出现内存错误!
    pFunc = PyObject_GetAttrString(py_module,"forward");       // 运行forward 函数
    if(pFunc == nullptr)
    {
        cout<<"Error: python pFunc_forward is null!"<<endl;
        return -1;
    }

    npy_intp Dims[3] = {img.rows,img.cols,3};
    PyObject *pyarray = PyArray_SimpleNewFromData(3,Dims,NPY_UBYTE,(void*)data);
    PyObject *argarray = PyTuple_New(1);
    PyTuple_SetItem(argarray,0,pyarray);
    PyObject *pRet = PyObject_CallObject(pFunc,argarray);   // 运行函数
    if(pRet == nullptr)
    {
        cout<<"Error: python pFunc_forward pRet is null!"<<endl;
        return -1;
    }


    Py_Finalize();


    return 0;
}`






// 当你的电脑在Ubuntu 必须存在 PIL 和 numpy 这些库,才可以导入成功,不然模块会导入失败!

**python  部分的代码,read_image.py:**



import sys       //  python 文件的路径 是在C++编译的路径,这一点需要注意
import numpy as np               
from PIL import Image

def forward(image):

    c=image[:,:,0]   #PIL是按照RGB 读取的,而Opencv 是BGR读取的,所以这里的c 和a 需要互换。
    b=image[:,:,1]
    a=image[:,:,2]

    a = np.expand_dims(a,axis=2)
    b = np.expand_dims(b,axis=2)
    c = np.expand_dims(c,axis=2)
    image = np.concatenate((a,b,c),axis=2)
    im = Image.fromarray(image)
    im.save("your_file.png")




CmakeList.txt   
cmake_minimum_required(VERSION 2.8)
set(OpenCV_DIR "/home/miao/otherpackage/opencv3.2/share/OpenCV" )
project(seg_on_deeplab)
set(CMAKE_CXX_STANDARD 14)
find_package(OpenCV REQUIRED)
INCLUDE_DIRECTORIES(${OpenCV_INCLUDE_DIRS} /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/)
set(PYTHON_INCLUDE_DIRS ${PYTHON_INCLUDE_DIRS} /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy)

message(STATUS ${OpenCV_INCLUDE_DIRS})
# 添加python 的头文件
find_package(PythonLibs 2.7 REQUIRED)
find_package(OpenCV REQUIRED)

include_directories(/usr/include/python2.7)
include_directories(${PYTHON_INCLUDE_DIRS})
# 链接python的 动态库
link_directories(/usr/lib/python2.7/config-x86_64-linux-gnu)
add_executable(seg_on_deeplab main.cpp)
# 链接 python 库
target_link_libraries(seg_on_deeplab libpython2.7.so ${OpenCV_LIBS})




















`
相关标签: pyhton c++ opencv