开发者

Compressing IplImage to JPEG using libjpeg in OpenCV

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;
  开发者_如何学Go      }
    }

    return 0;
}


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;

?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜