opencv - 在OpenCV中使用libjpeg将IplImage压缩为JPEG

所以我有这个问题。我有一个IplImage,我想将其压缩为JPEG并对其进行处理。我使用libjpeg8b。代码进入jpeg_start_compress()函数时退出,错误为“伪输入色彩空间”。这是我的代码。

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

最佳答案

我以前从未使用过libjpeg,但看起来您正在混合色彩空间。您将图像加载为灰度(CV_LOAD_IMAGE_GRAYSCALE),但告诉libjpeg它是RGB图像(JCS_RGB)。您是否尝试过换线

cinfo.in_color_space = JCS_RGB;


cinfo.in_color_space = JCS_GRAYSCALE;

https://stackoverflow.com/questions/5448957/

相关文章:

opencv - cvMatchTemplate()函数给出断言失败错误? OpenCV的

opencv - opencv中是否有用于处理Blob的好的库?

qt - 整合QT和OpenCV?

c# - 无法访问 C# emgucv 中的 Image.Data 属性

python - Python等效于cvCalcEigenObjects的函数

iphone - iOS + OpenCV - 垫内存泄漏

visual-studio-2010 - cvCreateButton VS2010

docker - 在 Windows 2019 服务器上运行 linux 容器时出错

opencv - 如何在ÅngströmLinux上安装OpenCV?

opencv - createVideoWriter()openCV中fps的最佳值