如何将python ndarray转换为c ++ char *?

时间:2019-05-29 11:23:09

标签: python c++ swig

我正在用swig包装一个c ++库,它需要以char *的形式获取图像数据。我可以在python中读取图像。但是如何将其转换为C ++?

我知道我可能需要使用typemap。我尝试了几种方法,但是我总是得到只有条纹的图片。

这是我的界面文件:

/* np2char */
%module np2char

%{
    #define SWIG_FILE_WITH_INIT
    #include <opencv2/opencv.hpp>
    using namespace cv;
%}

%inline %{
  typedef char* Image_Data_Type;
  typedef int Image_Width_Type;
  typedef int Image_Height_Type;

  struct Image_Info {
      Image_Data_Type imageData;
      Image_Width_Type imageWidth;
      Image_Height_Type imageHeight;
  };

  int Imageshow(Image_Info ImageInfo) {
      Mat img(ImageInfo.imageHeight, ImageInfo.imageWidth, CV_8UC3, ImageInfo.imageData);
      imshow("img_in_cpp", img);
      waitKey(0);
      destroyAllWindows();
      return 0;
  }

%}

这是我的setup.py:

"""
setup.py
"""
from distutils.core import setup,Extension

module1 = Extension('_np2char',
            sources=['np2char_wrap.cxx'],
            include_dirs=['include'],
            libraries = ["opencv_world342"],
            library_dirs=["lib"],
            )

setup(name = "np2char",
      version = "1.0",
      description = 'This package is used to trans ndarray to char*',
      ext_modules = [module1],
      py_modules=['np2char'])

这是我的python文件:

import np2char
import cv2

img1 = cv2.imread("1.jpg")

img_info = np2char.Image_Info()
img_info.imageData = img1.data
img_info.imageWidth = img1.shape[1]
img_info.imageHeight = img1.shape[0]

np2char.Imageshow(img_info)

我尝试过

%typemap(in) Image_Data_Type{
  $1 = reinterpret_cast<char*>(PyLong_AsLongLong($input));
}

,并且在python端 img_info.imageData=img1.ctypes.data 但是我仍然只有条纹。似乎图像数据已复制到内存中的其他位置。在此过程中,它被'\ 0'截断。

1 个答案:

答案 0 :(得分:0)

哈哈,我自己弄清楚的。
SWIG Documentation 5.5.2中,

  

SWIG假定已经使用malloc()动态分配了char *类型的所有成员,并且它们都是以NULL终止的ASCII字符串。

  如果此行为与您的应用程序所需的行为不同,则可以使用SWIG“ memberin”类型映射进行更改。

所以,我需要的是“ typemap(memberin)”:

%typemap(in) Image_Data_Type{
  $1 = reinterpret_cast<Image_Data_Type>(PyLong_AsLongLong($input));
}

%typemap(memberin) Image_Data_Type{
  $1 = $input;
}

%typemap(out) Image_Data_Type{
  $result = PyLong_FromLongLong(reinterpret_cast<__int64>($1));
}

使用整数传输指针有点丑陋。有没有更好的办法?

相关问题