chun2495 发表于 2018-11-14 13:35:33

帮忙看下如何快速实现灰阶图像转Jpg格式。

灰阶图像大小为400*400
每个像素点是8bit。

想请教各位:如何将这样的data转换成jpg格式,而且速度要快,我自己做的,大概需要几秒钟才可以转换一幅。
代码如下:
static struct APP0infotype {
      unsigned short int marker;// = 0xFFE0
      unsigned short int length; // = 16 for usual JPEG, no thumbnail
      unsigned char JFIFsignature; // = "JFIF",'\0'
      unsigned char versionhi; // 1
      unsigned char versionlo; // 1
      unsigned char xyunits;   // 0 = no units, normal density
      unsigned short int xdensity;// 1
      unsigned short int ydensity;// 1
      unsigned char thumbnwidth; // 0
      unsigned char thumbnheight; // 0
}APP0info = {0xFFE0,16,'J','F','I','F',0,1,1,0,1,1,0,0};

static structSOF0infotype {
      unsigned short int marker; // = 0xFFC0
      unsigned short int length; // = 17 for a truecolor YCbCr JPG
      unsigned char precision ;// Should be 8: 8 bits/sample
      unsigned short int height ;
      unsigned short int width;
      unsigned char nrofcomponents;//Should be 3: We encode a truecolor JPG
      unsigned char IdY;// = 1
      unsigned char HVY; // sampling factors for Y (bit 0-3 vert., 4-7 hor.)
      unsigned char QTY;// Quantization Table number for Y = 0
      unsigned char IdCb; // = 2
      unsigned char HVCb;
      unsigned char QTCb; // 1
      unsigned char IdCr; // = 3
      unsigned char HVCr;
      unsigned char QTCr; // Normally equal to QTCb = 1
}SOF0info = { 0xFFC0,17,8,0,0,3,1,0x11,0,2,0x11,1,3,0x11,1};
// Default sampling factors are 1,1 for every image component: No downsampling


//DQT说明:Define Quantization Table
static struct DQTinfotype
{
    unsigned short int marker;// = 0xFFDB
    unsigned short int length;// = 132
    unsigned char QTYinfo;// = 0:bit 0..3: number of QT = 0 (table for Y)
                  //       bit 4..7: precision of QT, 0 = 8 bit
    unsigned char Ytable;
    unsigned char QTCbinfo; // = 1 (quantization table for Cb,Cr)
    unsigned char Cbtable;
}DQTinfo;

// Ytable from DQTinfo should be equal to a scaled and zizag reordered version
// of the table which can be found in "tables.h": std_luminance_qt
// Cbtable , similar = std_chrominance_qt
// We'll init them in the program using set_DQTinfo function
//说明DHT:Define Huffman Table
/*
                                          哈夫曼编码表说明(是 "熵编码" 的一种形式)
    哈夫曼(Huffman)编码是一种常用的压缩编码方法,是Huffman于1952年为压缩文本文件建立的。它的基本原理是频繁使用的数据用较短的代码
代替,较少使用的数据用较长的代码代替,每个数据的代码各不相同。这些代码都是二进制码,且码的长度是可变的。举个例子:假设一个文件中
出现了8种符号S0,S1,S2,S3,S4,S5,S6,S7,那么每种符号要编码,至少需要3比特。假设编码成000,001,010,011,100,101,110,111(称做码字)。
那么符号序列S0S1S7S0S1S6S2S2S3S4S5S0S0S1编码后变成000001111000001110010010011100101000000001,共用了42比特。我们发现S0,S1,S2
这三个符号出现的频率比较大,其它符号出现的频率比较小,如果我们采用一种编码方案使得S0,S1,S2的码字短,其它符号的码字长,这样就
能够减少占用的比特数。例如,我们采用这样的编码方案:S0到S7的码字分别01,11,101,0000,0001,0010,0011,100,那么上述符号序列变成
011110001110011101101000000010010010111,共用了39比特,尽管有些码字如S3,S4,S5,S6变长了(由3位变成4位),但使用频繁的几个码字
如S0,S1变短了,所以实现了压缩。
    上述的编码是如何得到的呢?随意乱写是不行的。编码必须保证不能出现一个码字和另一个的前几位相同的情况,比如说,如果S0的码字为01,
S2的码字为011,那么当序列中出现011时,你不知道是S0的码字后面跟了个1,还是完整的一个S2的码字。我们给出的编码能够保证这一点。

下面给出具体的Huffman编码算法
(1)首先统计出每个符号出现的频率,上例S0到S7的出现频率分别为4/14,3/14,2/14,1/14,1/14,1/14,1/14,1/14
(2)从左到右把上述频率按从小到大的顺序排列
(3)每一次选出最小的两个值,作为二叉树的两个叶子节点,将和作为它们的根节点,这两个叶子节点不再参与比较,新的根节点参与比较
(4)重复(3),直到最后得到和为1的根节点
(5)将形成的二叉树的左节点标0,右节点标1。把从最上面的根节点到最下面的叶子节点途中遇到的0,1序列串起来,就得到了各个符号的编码

    产生Huffman编码需要对原始数据扫描两遍。第一遍扫描要精确地统计出原始数据中,每个值出现的频率,第二遍是建立Huffman树并进行编码。
由于需要建立二叉树并遍历二叉树生成编码,因此数据压缩和还原速度都较慢,但简单有效,因而得到广泛的应用

*/
static struct DHTinfotype
{
    unsigned short int marker;                // = 0xFFC4
    unsigned short int length;                //0x01A2
    unsigned char HTYDCinfo;             //bit 0..3: number of HT (0..3), for Y =0
                              //bit 4:type of HT, 0 = DC table,1 = AC table
                              //bit 5..7: not used, must be 0
    unsigned char YDC_nrcodes;       //at index i = nr of codes with length i
    unsigned char YDC_values;
    unsigned char HTYACinfo;             // = 0x10
    unsigned char YAC_nrcodes;
    unsigned char YAC_values;       //we'll use the standard Huffman tables
    unsigned char HTCbDCinfo;            // = 1
    unsigned char CbDC_nrcodes;
    unsigned char CbDC_values;
    unsigned char HTCbACinfo;            // = 0x11
    unsigned char CbAC_nrcodes;
    unsigned char CbAC_values;
}DHTinfo;

static struct SOSinfotype {
         unsigned short int marker;// = 0xFFDA
         unsigned short int length; // = 12
         unsigned char nrofcomponents; // Should be 3: truecolor JPG
         unsigned char IdY; //1
         unsigned char HTY; //0 // bits 0..3: AC table (0..3)
                   // bits 4..7: DC table (0..3)
         unsigned char IdCb; //2
         unsigned char HTCb; //0x11
         unsigned char IdCr; //3
         unsigned char HTCr; //0x11
         unsigned char Ss,Se,Bf; // not interesting, they should be 0,63,0
}SOSinfo={0xFFDA,12,3,1,0,2,0x11,3,0x11,0,0x3F,0};

typedef struct
{
    unsigned char B,G,R;
}colorRGB;

typedef struct
{
    unsigned char length;
    unsigned short int value;
}bitstring;

//extern unsigned char all_jpeg_data;
extern unsigned int all_jpeg_data_length;
unsigned int data2jpg(int image_w,int image_h,unsigned char *ImageData);

//通过查表,将RGB变成YCrBr
//因为进行DCT变换的数据必须在-128 -- 127之间,所以要减掉128;但从公式可见,只有R不是范围内,所以只有R减128
#defineY(R,G,B) ((unsigned char)( (YRtab[(R)]+YGtab[(G)]+YBtab[(B)])>>16 ) - 128)
#define Cb(R,G,B) ((unsigned char)( (CbRtab[(R)]+CbGtab[(G)]+CbBtab[(B)])>>16 ))
#define Cr(R,G,B) ((unsigned char)( (CrRtab[(R)]+CrGtab[(G)]+CrBtab[(B)])>>16 ))

#define writeword(w) writebyte((w)/256);writebyte((w)%256);

static unsigned char bytenew=0; // The byte that will be written in the JPG file
static signed char bytepos=7; //bit position in the byte we write (bytenew)
static unsigned short int mask={1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768};

//下面是我们要用到的哈夫曼表数据(两个直流分量,两个交流分量)
static bitstring YDC_HT;
static bitstring CbDC_HT;
static bitstring YAC_HT;
static bitstring CbAC_HT;

static unsigned char *category_alloc;
static unsigned char *category;            //Here we'll keep the category of the numbers in range: -32767..32767
static bitstring *bitcode_alloc;
static bitstring *bitcode;          // their bitcoded representation

//Precalculated tables for a faster YCbCr->RGB transformation
// We use a signed long int table because we'll scale values by 2^16 and work with integers
static signed long int YRtab,YGtab,YBtab;
static signed long int CbRtab,CbGtab,CbBtab;
static signed long int CrRtab,CrGtab,CrBtab;
static float fdtbl_Y;
static float fdtbl_Cb; //the same with the fdtbl_Cr

colorRGB *RGB_buffer; //image to be encoded
unsigned short int Ximage,Yimage;// image dimensions divisible by 8
static signed char YDU; // This is the Data Unit of Y after YCbCr->RGB transformation
static signed char CbDU;
static signed char CrDU;
static signed short int DU_DCT; // Current DU (after DCT and quantization) which we'll zigzag
static signed short int DU; //zigzag reordered DU which will be Huffman coded

//说明:按'之'字形量化DCT系数的序号,可以增加连续的0系数的个数
static unsigned char zigzag =
{
    0, 1, 5, 6,14,15,27,28,
    2, 4, 7,13,16,26,29,42,
    3, 8,12,17,25,30,41,43,
    9,11,18,24,31,40,44,53,
    10,19,23,32,39,45,52,54,
    20,22,33,38,46,51,55,60,
    21,34,37,47,50,56,59,61,
    35,36,48,49,57,58,62,63
};

//说明:下面是亮度与色度的量化表,本量化表经测试在电视图像是最佳的(除二后也可得到不错的效果)
//luminance:亮度      chrominance:色度
static unsigned char std_luminance_qt =
{
    16,11,10,16,24,40,51,61,
    12,12,14,19,26,58,60,55,
    14,13,16,24,40,57,69,56,
    14,17,22,29,51,87,80,62,
    18,22,37,56,68, 109, 103,77,
    24,35,55,64,81, 104, 113,92,
    49,64,78,87, 103, 121, 120, 101,
    72,92,95,98, 112, 100, 103,99
};
static unsigned char std_chrominance_qt =
{
    17,18,24,47,99,99,99,99,
    18,21,26,66,99,99,99,99,
    24,26,56,99,99,99,99,99,
    47,66,99,99,99,99,99,99,
    99,99,99,99,99,99,99,99,
    99,99,99,99,99,99,99,99,
    99,99,99,99,99,99,99,99,
    99,99,99,99,99,99,99,99
};
//Standard Huffman tables (cf. JPEG standard section K.3) */

//直流系数的编码(固定值)
static unsigned char std_dc_luminance_nrcodes = {0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0};
static unsigned char std_dc_luminance_values= {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

static unsigned char std_dc_chrominance_nrcodes = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0};
static unsigned char std_dc_chrominance_values= {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

//交流系数的编码(固定值)
static unsigned char std_ac_luminance_nrcodes = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d};
static unsigned char std_ac_luminance_values =
{
      0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
      0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
      0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
      0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
      0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
      0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
      0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
      0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
      0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
      0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
      0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
      0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
      0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
      0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
      0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
      0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
      0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
      0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
      0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
      0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
      0xf9, 0xfa
};

static unsigned char std_ac_chrominance_nrcodes = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77};
static unsigned char std_ac_chrominance_values =
{
      0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
      0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
      0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
      0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
      0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
      0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
      0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
      0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
      0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
      0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
      0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
      0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
      0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
      0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
      0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
      0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
      0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
      0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
      0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
      0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
      0xf9, 0xfa
};

#define QUA          50

#define MAIN_BUFFER_LENGTH        358752
#define CATEGORY_ALLOC        40000
#define BITCODE_ALLOC        (40000*1)                                //长为65535*3
#define SENDOR_SOURCE        (1280 * 1 * 8)                //sensor每次取8行数据,表示最多支持每行1280点,每点最多三字节
#define SENDOR_DEST                (1280 * 1 * 8)                //sensor采样转后后数据,必须是24位的
unsigned char g8main_bigbuffer;
unsigned char *gp8main_category = g8main_bigbuffer;
bitstring *gp8main_bitcode= (bitstring *)(g8main_bigbuffer + CATEGORY_ALLOC);
unsigned char *gp8main_sensor_source = g8main_bigbuffer + CATEGORY_ALLOC + BITCODE_ALLOC;
unsigned char *gp8main_sensor_dest   = g8main_bigbuffer + CATEGORY_ALLOC + BITCODE_ALLOC + SENDOR_SOURCE;

unsigned char all_jpeg_data;
unsigned int all_jpeg_data_length=0;

unsigned int ImageWdith=0;
unsigned int ImageHeight=0;
unsigned long int bytes_perline;

void writebyte(unsigned long int data)
{
        all_jpeg_data = data;
        all_jpeg_data_length++;
}

//Nothing to overwrite for APP0info
void write_APP0info()
{
        writeword(APP0info.marker);
        writeword(APP0info.length);
        writebyte('J');
        writebyte('F');
        writebyte('I');
        writebyte('F');
        writebyte(0);
        writebyte(APP0info.versionhi);
        writebyte(APP0info.versionlo);
        writebyte(APP0info.xyunits);
        writeword(APP0info.xdensity);
        writeword(APP0info.ydensity);
        writebyte(APP0info.thumbnwidth);
        writebyte(APP0info.thumbnheight);
}

// We should overwrite width and height
void write_SOF0info()
{
        writeword(SOF0info.marker);
        writeword(SOF0info.length);
        writebyte(SOF0info.precision);
        writeword(SOF0info.height);
        writeword(SOF0info.width);
        writebyte(SOF0info.nrofcomponents);
        writebyte(SOF0info.IdY);
        writebyte(SOF0info.HVY);
        writebyte(SOF0info.QTY);
        writebyte(SOF0info.IdCb);
        writebyte(SOF0info.HVCb);
        writebyte(SOF0info.QTCb);
        writebyte(SOF0info.IdCr);
        writebyte(SOF0info.HVCr);
        writebyte(SOF0info.QTCr);
}

void write_DQTinfo()
{
        unsigned char i;
        writeword(DQTinfo.marker);
        writeword(DQTinfo.length);
        writebyte(DQTinfo.QTYinfo);
        for (i=0;i<64;i++)
                writebyte(DQTinfo.Ytable);
        writebyte(DQTinfo.QTCbinfo);
        for (i=0;i<64;i++)
                writebyte(DQTinfo.Cbtable);
}

// Set quantization table and zigzag reorder it
void set_quant_table(unsigned char *basic_table,unsigned char scale_factor,unsigned char *newtable)
{
        unsigned char i;
        long temp;
        for (i = 0; i < 64; i++)
        {
                temp = ((long) basic_table * scale_factor + 50L) / 100L;
                /* limit the values to the valid range */
                if (temp <= 0L)
                        temp = 1L;
                if (temp > 255L)
                        temp = 255L; /* limit to baseline range if requested */
                newtable] = (unsigned char) temp;
        }
}

//DQT说明:Define Quantization Table
//功能:初始化量化表
void set_DQTinfo()
{
        unsigned char scalefactor = QUA;       
        DQTinfo.marker=0xFFDB;
        DQTinfo.length=132;
        DQTinfo.QTYinfo=0;
        DQTinfo.QTCbinfo=1;
        set_quant_table(std_luminance_qt,scalefactor,DQTinfo.Ytable);                //将亮度表写入Y表
        set_quant_table(std_chrominance_qt,scalefactor,DQTinfo.Cbtable);        //将色度表写入C表
}

//DHT说明:Define Huffman Table
//功能:初始化哈夫曼表
void write_DHTinfo()
{
        unsigned char i;
        writeword(DHTinfo.marker);
        writeword(DHTinfo.length);
        writebyte(DHTinfo.HTYDCinfo);
        for (i=0;i<16;i++)
                writebyte(DHTinfo.YDC_nrcodes);
        for (i=0;i<=11;i++)
                writebyte(DHTinfo.YDC_values);
        writebyte(DHTinfo.HTYACinfo);
        for (i=0;i<16;i++)
                writebyte(DHTinfo.YAC_nrcodes);
        for (i=0;i<=161;i++)
                writebyte(DHTinfo.YAC_values);
        writebyte(DHTinfo.HTCbDCinfo);
        for (i=0;i<16;i++)
                writebyte(DHTinfo.CbDC_nrcodes);
        for (i=0;i<=11;i++)
                writebyte(DHTinfo.CbDC_values);
        writebyte(DHTinfo.HTCbACinfo);
        for (i=0;i<16;i++)
                writebyte(DHTinfo.CbAC_nrcodes);
        for (i=0;i<=161;i++)
                writebyte(DHTinfo.CbAC_values);
}


//DHT:Define Huffman Table
//说明:将表数据填入DHT数据结构
void set_DHTinfo()
{
        unsigned char i;
        DHTinfo.marker=0xFFC4;
        DHTinfo.length=0x01A2;
        DHTinfo.HTYDCinfo=0;
        for (i=0; i<16; i++)
                DHTinfo.YDC_nrcodes = std_dc_luminance_nrcodes;
        for (i=0; i<=11; i++)
                DHTinfo.YDC_values = std_dc_luminance_values;
        DHTinfo.HTYACinfo = 0x10;
        for (i=0; i<16; i++)
                DHTinfo.YAC_nrcodes = std_ac_luminance_nrcodes;
        for (i=0;i<=161;i++)
                DHTinfo.YAC_values = std_ac_luminance_values;
        DHTinfo.HTCbDCinfo = 1;
        for (i=0;i<16;i++)
                DHTinfo.CbDC_nrcodes = std_dc_chrominance_nrcodes;
        for (i=0;i<=11;i++)
                DHTinfo.CbDC_values = std_dc_chrominance_values;
        DHTinfo.HTCbACinfo = 0x11;
        for (i=0;i<16;i++)
                DHTinfo.CbAC_nrcodes = std_ac_chrominance_nrcodes;
        for (i=0; i<=161; i++)
                DHTinfo.CbAC_values = std_ac_chrominance_values;
}

//Nothing to overwrite for SOSinfo
//说明SOS:Start of Scan
void write_SOSinfo()
{
        writeword(SOSinfo.marker);
        writeword(SOSinfo.length);
        writebyte(SOSinfo.nrofcomponents);
        writebyte(SOSinfo.IdY);
        writebyte(SOSinfo.HTY);
        writebyte(SOSinfo.IdCb);
        writebyte(SOSinfo.HTCb);
        writebyte(SOSinfo.IdCr);
        writebyte(SOSinfo.HTCr);
        writebyte(SOSinfo.Ss);
        writebyte(SOSinfo.Se);
        writebyte(SOSinfo.Bf);
}

//在文件数据内加入注释的,可以不用
void write_comment(char *comment)
{
        unsigned short int i,length;
        writeword(0xFFFE); //The COM marker
        length = strlen((const char *)comment);
        writeword(length+2);
        for (i=0; i<length; i++)
                writebyte(comment);
}

// A portable version; it should be done in assembler
void writebits(bitstring bs)
{
        unsigned short int value;
        signed char posval;//bit position in the bitstring we read, should be<=15 and >=0
        value=bs.value;
        posval=bs.length-1;
        while (posval>=0)
        {
                if (value & mask)
                        bytenew|=mask;
               
                posval--;
                bytepos--;
                if (bytepos<0)
                {
                        if (bytenew==0xFF)
                        {
                                writebyte(0xFF);
                                writebyte(0);
                        }
                        else
                        {
                                writebyte(bytenew);
                        }
                  bytepos=7;
                        bytenew=0;
                }
        }
}

//哈夫曼表的生成原理分析
//用常量表就可以生成哈夫曼表(两个常量表生成一个哈夫曼表)
void compute_Huffman_table(unsigned char *nrcodes,unsigned char *std_table,bitstring *HT)
{
        unsigned char k,j;
        unsigned char pos_in_table;
        unsigned short int codevalue;
        codevalue = 0;
        pos_in_table = 0;

        for (k=1; k<=16; k++)
        {
                for (j=1; j<=nrcodes; j++)
                {
                        HT].value = codevalue;
                        HT].length= k;
                        pos_in_table ++;
                        codevalue ++;
                }
                codevalue *= 2;
        }
}

//初始化哈夫曼表:只有四个表YDC,YAC,CbDC,CbAC(Cr的与Cb的相同)
void init_Huffman_tables()
{
        compute_Huffman_table(std_dc_luminance_nrcodes,std_dc_luminance_values,YDC_HT);
        compute_Huffman_table(std_dc_chrominance_nrcodes,std_dc_chrominance_values,CbDC_HT);
        compute_Huffman_table(std_ac_luminance_nrcodes,std_ac_luminance_values,YAC_HT);
        compute_Huffman_table(std_ac_chrominance_nrcodes,std_ac_chrominance_values,CbAC_HT);
}

//category:种类
//功能:生成category / bitcode两个数组,供压缩时使用
void set_numbers_category_and_bitcode()
{
        signed long int nr;
        signed long int nrlower,nrupper;
        unsigned char cat;

        category_alloc = gp8main_category;
        category = category_alloc+32767;

        bitcode_alloc = gp8main_bitcode;
        bitcode = bitcode_alloc+32767;
        nrlower = 1;
        nrupper = 2;

        //从数组的中间向两头写数据
        for (cat=1; cat<=15; cat++)
        {
                //Positive numbers
                for (nr=nrlower; nr<nrupper; nr++)
                {
                        category = cat;
                        bitcode.length = cat;
                        bitcode.value = (unsigned short int)nr;
                }

                //Negative numbers
                for (nr=-(nrupper-1); nr<=-nrlower; nr++)
                {
                        category = cat;
                        bitcode.length = cat;
                        bitcode.value = (unsigned short int)(nrupper-1+nr);
                }
                nrlower <<= 1;
                nrupper <<= 1;
        }
}

//说明:生成YCbCr表,供RGB转化时的查表
//Y(n)=0.114B(n)+0.587G(n)+0.299R(n)
//Cb(n)=0.5B(n)-0.3313G(n)-0.1687R(n)
//Cr(n)=0.0813B(n)-0.14187G(n)+0.5R(n)
void precalculate_YCbCr_tables()
{
        unsigned short int R,G,B;
        for (R=0;R<=255;R++)
        {
                YRtab=(signed long int)(65536*0.299+0.5)*R;
                CbRtab=(signed long int)(65536*-0.16874+0.5)*R;
                CrRtab=(signed long int)(32768)*R;
        }
        for (G=0;G<=255;G++)
        {
                YGtab=(signed long int)(65536*0.587+0.5)*G;
                CbGtab=(signed long int)(65536*-0.33126+0.5)*G;
                CrGtab=(signed long int)(65536*-0.41869+0.5)*G;
        }
        for (B=0;B<=255;B++)
        {
                YBtab=(signed long int)(65536*0.114+0.5)*B;
                CbBtab=(signed long int)(32768)*B;
                CrBtab=(signed long int)(65536*-0.08131+0.5)*B;
        }
}

//说明:8X8的区域进行DCT变换表的准备,即量化表fdtbl_Y / fdtbl_Cb
//生成本量化表时,只用生成一次,注重与ARM环境的差别
void prepare_quant_tables()
{
        double aanscalefactor =
        {
                1.0,
                1.387039845,
                1.306562965,
                1.175875602,
                1.0,
                0.785694958,
                0.541196100,
                0.275899379
        };
        unsigned char row, col;
        unsigned char i = 0;
        for (row = 0; row < 8; row++)
        {
                for (col = 0; col < 8; col++)
                {
                        fdtbl_Y = (float) (1.0 / ((double) DQTinfo.Ytable] *
                                aanscalefactor * aanscalefactor * 8.0));
                        fdtbl_Cb = (float) (1.0 / ((double) DQTinfo.Cbtable] *
                                aanscalefactor * aanscalefactor * 8.0));

                        i++;
                }
        }
}

//说明:前向DCT转换,并且进行量化
void fdct_and_quantization(signed char *data,float *fdtbl,signed short int *outdata)
{
        float tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
        float tmp10, tmp11, tmp12, tmp13;
        float z1, z2, z3, z4, z5, z11, z13;
        float *dataptr;
        float datafloat;
        float temp;
        signed char ctr;
        unsigned char i;
        for (i=0; i<64; i++)
                datafloat = data;

        //DCT转换第一步:按行处理
        dataptr=datafloat;
        for (ctr = 7; ctr >= 0; ctr--)
        {
                tmp0 = dataptr + dataptr;
                tmp7 = dataptr - dataptr;
                tmp1 = dataptr + dataptr;
                tmp6 = dataptr - dataptr;
                tmp2 = dataptr + dataptr;
                tmp5 = dataptr - dataptr;
                tmp3 = dataptr + dataptr;
                tmp4 = dataptr - dataptr;

                /* Even part */

                tmp10 = tmp0 + tmp3;        /* phase 2 */
                tmp13 = tmp0 - tmp3;
                tmp11 = tmp1 + tmp2;
                tmp12 = tmp1 - tmp2;

                dataptr = tmp10 + tmp11; /* phase 3 */
                dataptr = tmp10 - tmp11;

                z1 = (tmp12 + tmp13) * ((float) 0.707106781); /* c4 */
                dataptr = tmp13 + z1;        /* phase 5 */
                dataptr = tmp13 - z1;

                /* Odd part */

                tmp10 = tmp4 + tmp5;        /* phase 2 */
                tmp11 = tmp5 + tmp6;
                tmp12 = tmp6 + tmp7;

                /* The rotator is modified from fig 4-8 to avoid extra negations. */
                z5 = (tmp10 - tmp12) * ((float) 0.382683433); /* c6 */
                z2 = ((float) 0.541196100) * tmp10 + z5; /* c2-c6 */
                z4 = ((float) 1.306562965) * tmp12 + z5; /* c2+c6 */
                z3 = tmp11 * ((float) 0.707106781); /* c4 */

                z11 = tmp7 + z3;                /* phase 5 */
                z13 = tmp7 - z3;

                dataptr = z13 + z2;        /* phase 6 */
                dataptr = z13 - z2;
                dataptr = z11 + z4;
                dataptr = z11 - z4;

                dataptr += 8;                /* advance pointer to next row */
        }

        //DCT转换第二步:按列处理
        dataptr = datafloat;
        for (ctr = 7; ctr >= 0; ctr--)
        {
                tmp0 = dataptr + dataptr;
                tmp7 = dataptr - dataptr;
                tmp1 = dataptr + dataptr;
                tmp6 = dataptr - dataptr;
                tmp2 = dataptr + dataptr;
                tmp5 = dataptr - dataptr;
                tmp3 = dataptr + dataptr;
                tmp4 = dataptr - dataptr;

                /* Even part */

                tmp10 = tmp0 + tmp3;        /* phase 2 */
                tmp13 = tmp0 - tmp3;
                tmp11 = tmp1 + tmp2;
                tmp12 = tmp1 - tmp2;

                dataptr = tmp10 + tmp11; /* phase 3 */
                dataptr = tmp10 - tmp11;

                z1 = (tmp12 + tmp13) * ((float) 0.707106781); /* c4 */
                dataptr = tmp13 + z1; /* phase 5 */
                dataptr = tmp13 - z1;

                /* Odd part */

                tmp10 = tmp4 + tmp5;        /* phase 2 */
                tmp11 = tmp5 + tmp6;
                tmp12 = tmp6 + tmp7;

                /* The rotator is modified from fig 4-8 to avoid extra negations. */
                z5 = (tmp10 - tmp12) * ((float) 0.382683433); /* c6 */
                z2 = ((float) 0.541196100) * tmp10 + z5; /* c2-c6 */
                z4 = ((float) 1.306562965) * tmp12 + z5; /* c2+c6 */
                z3 = tmp11 * ((float) 0.707106781); /* c4 */

                z11 = tmp7 + z3;                /* phase 5 */
                z13 = tmp7 - z3;

                dataptr = z13 + z2; /* phase 6 */
                dataptr = z13 - z2;
                dataptr = z11 + z4;
                dataptr = z11 - z4;

                dataptr++;                        /* advance pointer to next column */
        }

        //DCT转换的结果存在datafloat

        //对DCT转换的结果进行量化处理,结果存在outdata[]内
        for (i = 0; i < 64; i++)
        {
                /* Apply the quantization and scaling factor */
                temp = datafloat * fdtbl;
                outdata = (signed short int) ((signed short int)(temp + 16384.5) - 16384);
        }
}

void process_DU(signed char *ComponentDU, float *fdtbl,signed short int *DC, bitstring *HTDC, bitstring *HTAC)
{
        bitstring EOB=HTAC;
        bitstring M16zeroes=HTAC;
        unsigned char i;
        unsigned char startpos;
        unsigned char end0pos;
        unsigned char nrzeroes;
        unsigned char nrmarker;
        signed short int Diff;

        //要函数进行DCT变换处理,并且进行量化,量化的结果存在DU_DCT内
        fdct_and_quantization(ComponentDU,fdtbl,DU_DCT);
        //==============================以下对量化的结果进行压缩==============================
        //对DU_DCT[]按 '之' 字重新排列,存在DU[]内
        for (i=0; i<=63; i++)
                DU] = DU_DCT;

        Diff = DU - *DC;                        //这里的*DC不一定是0
        *DC = DU;                                //因为这里会修改局部参数*DC

        //Encode DC
        if (Diff==0)
                writebits(HTDC);                        //Diff might be 0
        else
        {
                writebits(HTDC]);
                writebits(bitcode);
        }

        //Encode ACs
        //先将后面的0全找出来,真正要处理的是头部的非零部分
        for (end0pos=63; (end0pos>0)&&(DU==0); end0pos--);

        //end0pos = first element in reverse order !=0
        if (end0pos==0)
        {
                writebits(EOB);
                return;
        }

        //非零部分的处理方法
        //但是非零部分的内部,可能还有单个或连续的零,也要过滤掉,不处理
        //所以真正处理的,只有非零部分内的非零的数据
        i=1;
        while (i <= end0pos)
        {
                startpos=i;

                //过滤掉里面的0
                for (; (DU==0)&&(i<=end0pos);i++) ;

                nrzeroes = i-startpos;
                //如果内部连续0个数超过16个要做以下处理
                if (nrzeroes>=16)
                {
                        for (nrmarker=1; nrmarker<=nrzeroes/16; nrmarker++)
                                writebits(M16zeroes);
                        nrzeroes = nrzeroes%16;
                }

                writebits(HTAC]]);
                writebits(bitcode]);
                i++;
        }
        //EOB是每帧数据(8*8)的结束村记
        if (end0pos!=63)
                writebits(EOB);
}


/*=============================================================================
功能说明:
                将8行的sensor数据加载到gp8main_sensor_source,并且变成24bit数据后放到
                gp8main_sensor_dest
返回:
                NULL
备注:
                本函数是摸拟ARM来做,因为真正的数据来自于sensor
//===========================================================================*/
void main_load8line_form_sensor(unsigned short int linenum,unsigned char *data)
{
        unsigned long int tmp01,tmp02;       

        unsigned long int         perline_dest = bytes_perline * 3 ;

        gp8main_sensor_source = (unsigned char*)data+(linenum*bytes_perline);
       
        //16bit的数据转成24bit
        for(tmp01 = 0; tmp01 < 8; tmp01 ++)
        {
                for(tmp02 = 0; tmp02 < ImageWdith; tmp02 ++)
                {
                        gp8main_sensor_dest[(tmp01)*perline_dest + tmp02*3 + 2] = gp8main_sensor_source;
                        gp8main_sensor_dest[(tmp01)*perline_dest + tmp02*3 + 0] = gp8main_sensor_source;
                        gp8main_sensor_dest[(tmp01)*perline_dest + tmp02*3 + 1] = gp8main_sensor_source;
                }
        }

        tmp01 = 0;
}

//将8X8单元RGB数据从RGB_buffer[]内取出,转成YCbCr,同时存储到YDU[]/CbDU[]/CrDU[]内去
void load_data_units_from_RGB_buffer(unsigned short int xpos,unsigned short int ypos)
{
        unsigned char x,y;
        unsigned char pos=0;
        unsigned long int location;
        unsigned char R,G,B;
        location = xpos;
        for (y=0; y<8; y++)
        {
                for (x=0; x<8; x++)
                {
                        R = ((colorRGB *)gp8main_sensor_dest).R;
                        G = ((colorRGB *)gp8main_sensor_dest).G;
                        B = ((colorRGB *)gp8main_sensor_dest).B;
                        YDU=Y(R,G,B);
                        CbDU=Cb(R,G,B);
                        CrDU=Cr(R,G,B);
                        location++;
                        pos++;
                }
                location += ImageWdith-8;                                //换行
        }
}

void main_encoder(unsigned char *image)
{
        signed short int DCY=0,DCCb=0,DCCr=0; //DC coefficients used for differential encoding
        unsigned short int xpos,ypos;
        for(ypos=0;ypos<ImageHeight;ypos += 8)
        {
                main_load8line_form_sensor(ypos,image);
                for(xpos=0;xpos<ImageWdith;xpos += 8)
                {
                        load_data_units_from_RGB_buffer(xpos,ypos);
                        //对Y,Cb,Cr各自进行量化(Y量化表,Cb与Cr表相同)
                        process_DU(YDU,fdtbl_Y,&DCY,YDC_HT,YAC_HT);
                        process_DU(CbDU,fdtbl_Cb,&DCCb,CbDC_HT,CbAC_HT);
                        process_DU(CrDU,fdtbl_Cb,&DCCr,CbDC_HT,CbAC_HT);
                }
        }
}

void init_all()
{
        set_DQTinfo();
        set_DHTinfo();
        init_Huffman_tables();
        set_numbers_category_and_bitcode();
        precalculate_YCbCr_tables();
        prepare_quant_tables();
}

//        入口函数
//        image_w 和image_h为图像的宽和高,一定要为8的倍数
//ImageData 为原始图像数据
//        图像输出地址在JPG_filename中

unsigned int data2jpg(int image_w,int image_h,unsigned char *ImageData)
{
//        unsigned int i;
//        char JPG_filename = "c:/test.jpg";
        bitstring fillbits;                                                                        //filling bitstring for the bit alignment of the EOI marker

        all_jpeg_data_length=0;

        ImageWdith = image_w;
        ImageHeight = image_h;

        bytes_perline = ((ImageWdith * 1 + 3) / 4) * 4;
        init_all();
        SOF0info.width = (unsigned short int)ImageWdith;                //Ximage_original;
        SOF0info.height = (unsigned short int)ImageHeight;                //Yimage_original;
        writeword(0xFFD8); //SOI
        write_APP0info();
        write_DQTinfo();
        write_SOF0info();
        write_DHTinfo();
        write_SOSinfo();

        bytenew = 0;
        bytepos = 7;
        main_encoder(ImageData);
        //Do the bit alignment of the EOI marker
        if (bytepos>=0)
        {
                fillbits.length=bytepos+1;
                fillbits.value=(1<<(bytepos+1))-1;
                writebits(fillbits);
        }
        writeword(0xFFD9); //EOI
    return all_jpeg_data_length;
}

t3486784401 发表于 2018-11-14 19:54:49

运行平台呢?打算跑 FPGA 么?这个代码看不出 HDL 的影子啊。

Windows 下倒是可以用 Gdiplus 做,系统标准的图像库,可以创建/保存 BMP/JPG/PNG/GIF/TIFF 格式图片。
流程大致是:创建 Gdiplus::Bitmap 实例 -> 获取图像数据区指针并访问(写入你的图像) -> Gdiplus::Bitmap::Save 指定使用 JPG 编码器。

当然 JPG 编出来是有损的,推荐使用 PNG。

jm2011 发表于 2018-11-15 14:39:16

1:如果是灰度图的话,只用处理Y分量
2:代码里面大量的浮点运算,而且有一次RGB到YUV的转换。看看输入能不能改为YUV的数据;
3:为什么不直接使用libjpeg等开源库
4:代码要是在ARM上运行,建议使用NEON进行优化
5:各个模块做成异步的,例如,RGB2YUV和DCT变换可以做成流水线的

另外代码可能有问题,没有跑通,例如:“//16bit的数据转成24bit”的部分;

chun2495 发表于 2018-11-15 16:21:16

t3486784401 发表于 2018-11-14 19:54
运行平台呢?打算跑 FPGA 么?这个代码看不出 HDL 的影子啊。

Windows 下倒是可以用 Gdiplus 做,系统标准 ...

fpga内核搞,相当于纯C语言做jpg

chun2495 发表于 2018-11-15 16:22:25

jm2011 发表于 2018-11-15 14:39
1:如果是灰度图的话,只用处理Y分量
2:代码里面大量的浮点运算,而且有一次RGB到YUV的转换。看看输入能不 ...

是啊 ,标准的库中,大量的float运算,各种嵌套循环,100M的内核跑起来生不如死。

chun2495 发表于 2018-11-15 16:23:56

另外 这个问题已经解决了,用的是自己写的行程编码方式。
页: [1]
查看完整版本: 帮忙看下如何快速实现灰阶图像转Jpg格式。