TypeError:ctype'unsigned int *'的初始化程序必须是cdata指针,而不是字节

时间:2019-03-16 10:52:33

标签: python-3.6 python-cffi leptonica

我尝试将PIL图像转换为leptonica PIX。这是我的代码python 3.6:

import os, cffi
from PIL import Image

# initialize leptonica
ffi = cffi.FFI()
ffi.cdef("""
    typedef int           l_int32;
    typedef unsigned int  l_uint32;
    struct                Pix;
    typedef struct Pix    PIX;
    PIX * pixCreate       (int width, int height, int depth);
    l_int32 pixSetData    (PIX *pix, l_uint32 *data);
""")
leptonica = ffi.dlopen(os.path.join(os.getcwd(), "leptonica-1.78.0.dll"))

# convert PIL to PIX
im = Image.open("test.png").convert("RGBA")
depth = 32
width, height = im.size
data = im.tobytes("raw", "RGBA")
pixs = leptonica.pixCreate(width, height, depth)
leptonica.pixSetData(pixs, data)

pixSetData失败,并显示消息:TypeError: initializer for ctype 'unsigned int *' must be a cdata pointer, not bytes。 如何将字节对象(data)转换为cdata指针?

2 个答案:

答案 0 :(得分:0)

我从Armin Rigo at python-cffi forum得到了答案:

  

假设您拥有最新的cffi 1.12,则可以执行以下操作:

   leptonica.pixSetData(pixs, ffi.from_buffer("l_uint32[]", data))
     

向后兼容的方法更加复杂,因为我们需要   确保中间对象保持活动状态:

   p = ffi.from_buffer(data)
   leptonica.pixSetData(pixs, ffi.cast("l_uint32 *", p))
   # 'p' must still be alive here after the call, so put it in a variable above!

答案 1 :(得分:0)

PIL和Leptonica似乎没有完全相同的原始格式。最后,RGBA与ABGR。对我有用的是使用未压缩的TIFF作为快速可靠的数据交换格式。

# Add these to ffi.cdef():
# 
# typedef unsigned char l_uint8;
# PIX * pixReadMem(const l_uint8 *data, size_t size);
# l_ok pixWriteMem(l_uint8 **pdata, size_t *psize, PIX *pix, l_int32 format);

from io import BytesIO
import PIL.Image

IFF_TIFF = 4


def img_pil_to_lepto(pilimage):
    with BytesIO() as bytesio:
        pilimage.save(bytesio, 'TIFF')
        tiff_bytes = bytesio.getvalue()

    cdata = ffi.from_buffer('l_uint8[]', tiff_bytes)
    pix = leptonica.pixReadMem(cdata, len(tiff_bytes))
    return pix


def img_lepto_to_pil(pix):
    cdata_ptr = ffi.new('l_uint8**')
    size_ptr = ffi.new('size_t*')
    leptonica.pixWriteMem(cdata_ptr, size_ptr, pix, IFF_TIFF)
    cdata = cdata_ptr[0]
    size = size_ptr[0]

    tiff_bytes = bytes(ffi.buffer(cdata, size))
    with BytesIO(tiff_bytes) as bytesio:
        pilimage = PIL.Image.open(bytesio).copy()
        return pilimage