Compressing IplImage to JPEG using libjpeg in OpenCV

醉酒当歌 提交于 2019-12-22 01:07:06

问题


So I have this problem. I have an IplImage that i want to compress to JPEG and do something with it. I use libjpeg8b.The code exit when it goes the function of jpeg_start_compress() with an error of "Bogus input colorspace" .Here are my code.

#include "highgui.h"
#include <stdio.h>
#include "jpeglib.h"
#include "cv.h"
#include <iostream>
#include <fstream>
using namespace std;
using namespace cv;

#pragma comment(lib, "jpeglib.lib")


bool ipl2jpeg(IplImage *frame, unsigned char **outbuffer, unsigned long*outlen) 
{
    IplImage *img  = new IplImage;
    memcpy(img,frame,frame->nSize);
    unsigned char *outdata = (uchar *) img->imageData;
    struct jpeg_compress_struct cinfo = {0};
    struct jpeg_error_mgr jerr;
    JSAMPROW row_ptr[1];
    int row_stride;

    *outbuffer = NULL;
    *outlen = 0;

    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_compress(&cinfo);
    jpeg_mem_dest(&cinfo, outbuffer, outlen);

    cinfo.image_width = frame->width;
    cinfo.image_height = frame->height;
    cinfo.input_components = frame->nChannels;
    cinfo.in_color_space = JCS_RGB;

    jpeg_set_defaults(&cinfo);
    jpeg_start_compress(&cinfo, TRUE);
    system("pause");
    row_stride = frame->width * frame->nChannels;


    while (cinfo.next_scanline < cinfo.image_height)
    {
        row_ptr[0] = &outdata[cinfo.next_scanline * row_stride];
        jpeg_write_scanlines(&cinfo, row_ptr, 1);
    }

    jpeg_finish_compress(&cinfo);
    jpeg_destroy_compress(&cinfo);

    return true;

}


int main()
{
    ofstream fout("text.txt");
    unsigned char **buf;
    buf  = new unsigned char* [120];
    for(int i=0;i<500;i++)
    {
        buf[i] = new unsigned char[120];
    }

    for(int i=0;i< 120;i++)
    {
        for(int j=0;j<120;j++)
        {
            buf[i][j]  = 0;
        }
    }

    unsigned long *len = new unsigned long;
    *len = 120*120;
    Ptr<IplImage> img = cvLoadImage("test.jpg",CV_LOAD_IMAGE_GRAYSCALE);
    ipl2jpeg(img,buf,len);

    for(int i=0;i< 120;i++)
    {
        for(int j=0;j<120;j++)
        {
            fout<<buf[i][j]<<endl;
        }
    }

    return 0;
}

回答1:


I've never used libjpeg before, but it looks like you're mixing color spaces. You load the image as a grayscale (CV_LOAD_IMAGE_GRAYSCALE), but are telling libjpeg that it's an RGB image (JCS_RGB). Have you tried changing the line

cinfo.in_color_space = JCS_RGB;

to

cinfo.in_color_space = JCS_GRAYSCALE;

?




回答2:


Is there any reason why you're not using opencv's native JPEG support?

cvSaveImage(frame, "frame.jpeg");

The documentation is here.

EDIT

If you insist on using libjpeg, have a look at this post.



来源:https://stackoverflow.com/questions/5448957/compressing-iplimage-to-jpeg-using-libjpeg-in-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!