[英]how to convert python ndarray to c++ char*?
我正在使用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
但我仍然只有条纹。 似乎imagedata被复制到内存中的其他位置。 在此过程中,它被'\\ 0'截断。
哈哈,我自己想通了。
在SWIG文档5.5.2中 ,
SWIG假定char *类型的所有成员都已使用malloc()动态分配,并且它们是以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));
}
使用整数传输指针有点难看。 有没有更好的办法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.