[C++-sig] help passing image data

Stefan Seefeld seefeld at sympatico.ca
Tue May 23 22:25:43 CEST 2006


J.D. Yamokoski wrote:
> I am writing a simple test application to teach myself the ins and outs 
> of embedding Python in a C++ program. But I am currrently stuck trying 
> to pass non-standard data across the C/Python interface. Plus I may be 
> complicating matters by trying to do all this embedding in MFC, but 
> thats what I know for GUI programming. Here are the details:

Have you looked at the libs/python/test/exec.cpp tests in the boost
source package ? I think it demonstrates how to do what you want.
Here is (roughly) what you need to do:

* Create bindings for your C++ data types, i.e. using the class_<>
   machinery.

* Inject the new types, as well as any global objects you want to
   access from within python into a python dictionary that will be
   the script's environment.

* Execute your python script.

> Using boost.python, I have created a module of the CImg 
> (http://cimg.sourceforge.net/) library - a very light module as it only 
> supports a handful of functions. I know python extensions for image 
> manipulation already exist but this was to practice with boost - plus my 
> main app already uses CImg.
> 
> My test app is a SDI MFC program. In the document, I have one member 
> variable - a CImg object. Image data stored in this object is displayed 
> in the main window of the app.
> 
> Now for the python. The app has a popup window where I can type in text 
> which is then passed to the interpreter. For instance (please excuse any 
> blatant python errors - treat this as pseudo python code):
> 
> # Import my CImg extension and the set/get function from the main app
> import CImg
> import MyAppInterface
> 
> # Get the image from the app. Function should return a CImg object
> DocImg = MyAppInterface.GetCurrentImage()
> 
> # Call some CImg function
> DocImg.blur()
> 
> # Return the data to the app for displaying
> MyAppInterface.SetCurrentImage( DocImg )

FWIW, the GetCurrentImage() call above may return a handle to an existing
image, instead of returning a copy. In that case you would modify it in-place,
and thus there wouldn't be any need to call SetCurrentImage().


> 					
> 
> To create the application interface functions, I have the following code 
> in C:
> 
> static PyObject*
> get_current_image(PyObject *self, PyObject *args)
> {
>      if( !PyArg_ParseTuple(args, "") ) return NULL;
> 
>      CImg<float> img = gDocument->getCurrentImage();
> 
>      return Py_BuildValue("o", &img);
> };

This isn't needed, if you use python::class_<Cimg<float> > to export your
Cimg<> type to python. Please have a look into the above test / demo code.
It is very compact and should do all you need.

HTH,
		Stefan



More information about the Cplusplus-sig mailing list