libccv - 如何从内存中的字节读取图像

libccv - how to read image from bytes in memory

我正在尝试将 libccv 与 Python 一起使用(我已经使用 SWIG 创建了包装器)。我的情况如下:

  1. 我有内存图像
  2. 我想将此图像(字节)传递给 C 函数,用 SWIG 包装 Python。
  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 参数的一些组合,但每次我得到 SIGSEVimage 变量是 0.

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

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

我想通了,诀窍是使用 fmemopen() 函数,将内存作为流打开, API 可以进一步读取它,它接受 FILE* 指针。

完整代码:

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
    }
}

来自 Python 的用法(在使用 SWIG 构建 C 代码之后):

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

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