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

2024-04-19 09:13:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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;
  }

%}

这是我的设置.py公司名称:

^{pr2}$

这是我的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 但我还是只有条纹。似乎imagedata被复制到内存中的其他位置。在此过程中,它被“\0”截断。在


Tags: imageinfoimgdatatypeintimg1char
1条回答
网友
1楼 · 发布于 2024-04-19 09:13:22

哈哈,我自己想出来的。
SWIG Documentation 5.5.2

SWIG assumes that all members of type char * have been dynamically allocated using malloc() and that they are NULL-terminated ASCII strings.

If this behavior differs from what you need in your applications, the SWIG "memberin" typemap can be used to change it.

所以,我需要的是“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));
}

使用整数来传输指针有点难看。有更好的方法吗?在

相关问题 更多 >