简体   繁体   中英

how to convert python ndarray to c++ char*?

I'm using swig to wrap a c++ library, it needs to get image data as char*. I can read the image in python. But how can i trans it to c++?

I konw I might need to use typemap. I tried several ways, but I always get a picture with only stripes.

This is my interface file:

/* 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;
  }

%}

This is my 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'])

and this is my python file:

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)

I have tried

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

, and in python side img_info.imageData=img1.ctypes.data But still I got only stripes. It seems that imagedata is copied to other places in memory. In the process, it was truncated by '\\0'.

haha, I figured it out myself.
In 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.

So, what I need is "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));
}

It's a bit ugly using integer to transfer pointer. Is there a better way?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM