0

I am trying to use swig to wrap some c++ code to pass a numpy array back to python. I am following some examples I have seen online to use numpy.i. Here is what my code looks like.

I am using this as the function definition in my class header file:

bool grabFrame(int buf_size, unsigned char *buf);

In my interface file I have:

/* File : OV4682Interface.i */
%module OV4682Interface
%include "std_string.i"

%{
    #define SWIG_FILE_WITH_INIT
    #include "OV4682FrameGrabber.h"
%}

%include "numpy.i"
%init %{
    import_array();
%}

%apply (int DIM1, unsigned char* ARGOUT_ARRAY1) {(int buf_size, unsigned char *buf)};

%include "../inc/OV4682FrameGrabber.h"

My Python code looks like this:

import numpy as np
import OV4682Interface as ov

width = 672
height = 380
buf_size = width*height*2

buf = np.zeros(buf_size, dtype=np.uint8)

grab = ov.OV4682FrameGrabber()
grab.grabFrame(buf)

When I run this I get the following error:

Traceback (most recent call last): File "OV4682FrameGrabberTest.py", line 44, in grab.grabFrame(buf) File "/home/ubuntu/rgb_ir_frame_grabber/build/lib/OV4682Interface.py", line 117, in grabFrame def grabFrame(self, *args): return _OV4682Interface.OV4682FrameGrabber_grabFrame(self, *args) TypeError: Int dimension expected. 'unknown type' given.

For some reason I am getting an error saying the type is unknown for the passed in array, but I have explicitly set the dtype to be np.uint8. I was wondering if anyone can point me to what I am doing incorrectly here as I am a bit stumped.

1 Answer 1

0

Looks like I did not look closely enough at the answer for this post (SWIG+c+Python: Passing and receiving c arrays). I did not notice that swig adds the output array to the return list and just wants the size of the array passed in.

I changed the method definition to this:

void grabFrame(int buf_size, unsigned char *buf);

and I changed the python call to be this:

buf = grab.grabFrame(np.shape(buf)[0])

This now works and returns the array of data I wanted.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.