尝试使用libjpeg将YUV图像压缩为jpeg时出现奇怪的图像

时间:2013-06-10 17:01:53

标签: c++ c qt opencv jpeg

我使用Qt,OpenCV和libJpeg来压缩YUV422图像,但输出不正确。

here is the output image

如果我将yuv转换为rgb然后压缩,我得到一个正确的输出,但我明白Jpeg在内部使用YUV,这就是我想删除冗余的原因。

这是我的代码:

bool ipl2jpeg(IplImage *frame, unsigned char **outbuffer, long unsigned int *outlen) {
    unsigned char *outdata = (uchar *) frame->imageData;
    struct jpeg_compress_struct cinfo ;
    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_YCbCr;

    jpeg_set_defaults(&cinfo);
    jpeg_set_quality (&cinfo,100 , true);
    jpeg_start_compress(&cinfo, TRUE);
    row_stride = frame->width *2;// frame->nChannels;

    while (cinfo.next_scanline < cinfo.image_height) {
        /* jpeg_write_scanlines expects an array of pointers to scanlines.
         * Here the array is only one element long, but you could pass
         * more than one scanline at a time if that's more convenient.
         */
        row_ptr[0] = &outdata[cinfo.next_scanline * row_stride];
        (void) jpeg_write_scanlines(&cinfo, row_ptr, 1);
      }

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

    return true;

}

有什么问题?

Here is the YUV image

2 个答案:

答案 0 :(得分:1)

提供的图像文件(frame-3.raw)是YUYV格式的640x480

以下代码

JSAMPROW row_pointer[1];
row_pointer[0] = row_buf;
while (cinfo.next_scanline < cinfo.image_height) {
    unsigned i, j;
    unsigned offset = cinfo.next_scanline * cinfo.image_width * 2;
    for (i = 0, j = 0; i < cinfo.image_width*2; i += 4, j += 6) {
        row_buf[j + 0] = buf[offset + i + 0]; // Y
        row_buf[j + 1] = buf[offset + i + 1]; // U
        row_buf[j + 2] = buf[offset + i + 3]; // V
        row_buf[j + 3] = buf[offset + i + 2]; // Y
        row_buf[j + 4] = buf[offset + i + 1]; // U
        row_buf[j + 5] = buf[offset + i + 3]; // V
    }        
    jpeg_write_scanlines(&cinfo, row_pointer, 1);
}

放在jpeg_start_compress()和jpeg_finish_compress()之间正确创建JPEG文件而不进行颜色空间转换(但是使用上采样)

jason_s的代码看起来也是正确的

答案 1 :(得分:0)

我不认为libjpeg会接受二次采样的图像数据作为输入。所以,你必须先取消它的子样本。

您可以分配一个临时行缓冲区,并转换每一行,如下所示:

for (i=0; i<frame->width; i++) {
    tmpbuf[i*3+0] = outdata[cinfo.next_scanline * row_stride + i*2];
    tmpbuf[i*3+1] = outdata[cinfo.next_scanline * row_stride + (i-i%2)*2+1];
    tmpbuf[i*3+2] = outdata[cinfo.next_scanline * row_stride + (i-i%2)*2+3];
}
row_ptr[0] = tmpbuf;