Compressing IplImage to JPEG using libjpeg in OpenCV

后端 未结 4 2059
长发绾君心
长发绾君心 2020-12-09 07:05

So I have this problem. I have an IplImage that i want to compress to JPEG and do something with it. I use libjpeg. I found a lot of answers \"read through examples and docs

4条回答
  •  轮回少年
    2020-12-09 07:43

    After fighting with libJpeg for 2 days (pointers, memory stepping, and pulling hair) I gave up and used the all favourite save-to-disk-load-to-memory approach, so if anybody is interested here is the method:

    char* convert2jpeg(IplImage* frame, int* frame_size) {
    
    FILE* infile = NULL;
    struct stat fileinfo_buf;
    
    if (cvSaveImage(name_buf, frame) < 0) {
        printf("\nCan't save image %s", name_buf);
        return NULL;
    }
    
    if (stat(name_buf, &fileinfo_buf) < 0) {
        printf("\nPLAYER [convert2jpeg] stat");
        return NULL;
    }
    
    *frame_size = fileinfo_buf.st_size;
    char* buffer = (char *) malloc(fileinfo_buf.st_size + 1);
    
    if ((infile = fopen(name_buf, "rb")) == NULL) {
        printf("\nPLAYER [convert2jpeg] fopen %s", name_buf);
        free(buffer);
        return NULL;
    }
    
    fread(buffer, fileinfo_buf.st_size, 1, infile);
    fclose(infile);
    
    return buffer;
    }
    

    I hope somebody finds this usefull. I wish somebody from OpenCV developers sees this thread and implements direct to buffer JPEG conversion in OpenCV and spares us the misery and 1 save/load to disk operation.

提交回复
热议问题