简体   繁体   中英

Passing an image from C++ to Python 3.4

I am using a Python interpreter embedded in a C++ program to generate reports. As part of the report, the Python script grabs image data from the C++ program and building a PIL Image from it as follows:

width = getImageWidth ()
height = getImageHeight ()
pixels = getImagePixels ()

pilTile = Image.frombuffer ('RGB',
                            (width, height),
                            pixels,
                            'raw',
                            'RGB',
                            0,
                            -1)

On the C++ side of things, I've been returning the image pixels as a buffer using Boost.Python :

object getImagePixels ()
{
    GLubyte *buf = getImage () ;
    size_t size = getSize () ;

    object obj = object ((handle<>(borrowed (PyBuffer_FromMemory (
        (char *) buf, size, PyBUF_READ))))) ; 
    return obj ;
}

The problem is, Python 3.x eliminates the PyBuffer_FromMemory interface. I've tried replacing it with PyMemoryView_FromMemory , but PIL doesn't seem to be able to use memoryviews.

What is the best way to replace PyBuffer_FromMemory here?

Thanks for your help!

This is somewhat round-about, but if you have numpy you can do

#include <numpy/arrayobject.h>

...
PyObject* pyArray = PyArray_SimpleNewFromData(1, size, NPY_BYTE, (void*)buf));

( Documentation )

I'm not 100% on how Boost.Python works, but glancing at the docs, handle holds anything derived from PyObject , so it should work.

It may also work to just return the numpy array directly and use Image.fromarray()

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