2017-08-10 35 views
1

我正在尝试在Python中使用libccv(我使用SWIG创建了包装器)。我的情况是这样的:libccv - 如何从内存中的字节读取图像

  1. 我已经在内存中的图像
  2. 我想通过这种图像(字节)C函数,裹的Python与SWIG。
  3. C代码将处理的图像与libccv功能

Python代码:

bytes = open("input.jpg","rb").read() 
result = ccvwrapper.use_ccv(bytes, 800, 600) 

的C代码:

int use_ccv(char *bytes, int width, int height){ 
    int status = 0; 
    ccv_enable_default_cache(); 
    ccv_dense_matrix_t* image = 0; 
    ccv_read(bytes, &image, CCV_IO_ANY_RAW, width, height, width * 3); 

    if (image != 0) 
    { 
     //process the image 
     ccv_matrix_free(image); 
     status = 1; 
    } 
    ccv_drain_cache(); 

    return status; 
} 

我已经试过的ccv_readtype, rows, cols, scanline参数几个组合但每次我得到SIGSEV或th e image变量是0

我不想使用ccv_read函数重载,它采用文件路径,因为我不想介绍将映像写入磁盘的开销。

什么是使用libccv从内存中读取图像的正确方法?

+0

您传递给C函数的指针是有效的(* bytes ptr)?我的意思是,一个健全的检查可能是好的,以防万一。 – phyloflash

+0

是的,它是有效的。我可以用C函数中的''''fwrite()''将这些字节写回到文件中,并且它产生完全相同的图像。 –

回答

0

我已经想通了,的伎俩是使用fmemopen()功能,打开内存流,这进一步可以通过API,它们接受FILE*指针读取。

全码:从Python的

int* swt(char *bytes, int array_length, int width, int height){ 
    ccv_dense_matrix_t* image = 0; 

    FILE *stream; 
    stream = fmemopen(bytes, array_length, "r"); 
    if(stream != NULL){ 
     int type = CCV_IO_JPEG_FILE | CCV_IO_GRAY; 
     int ctype = (type & 0xF00) ? CCV_8U | ((type & 0xF00) >> 8) : 0; 
     _ccv_read_jpeg_fd(stream, &image, ctype); 
    } 
    if (image != 0){ 
     // here we have access to image in libccv format, so any processing can be done 
    } 
} 

用法(建设有SWIG的C代码之后):

import ccvwrapper 
bytes = open("test_input.jpg", "rb").read() 
results = ccvwrapper.swt(bytes, len(bytes), 1024, 1360) # width:1024, height:1360 

我已经在博客中解释所有的细节:http://zablo.net/blog/post/stroke-width-transform-swt-python