一、实验目的
掌握JPEG编解码系统的基本原理。初步掌握复杂的数据压缩算法实现,并能根据理论分析需要实现所对应数据的输出。
二、实验原理
1.JPEG编解码原理
JPEG( Joint Photographic Experts Group)即联合图像专家组,是用于连续色调静态图像压缩的一种标准,文件后缀名为.jpg或.jpeg,是最常用的图像文件格式。其主要是采用预测编码(DPCM)、离散余弦变换(DCT)以及熵编码的联合编码方式,以去除冗余的图像和彩色数据,属于有损压缩格式,它能够将图像压缩在很小的储存空间,一定程度上会造成图像sh的损数据尤其是使用过高的压缩比例,将使最终解压缩后恢复的图像质量降低,如果追求高品质图像,则不宜采用过高的压缩比例。JPEG压缩技术十分先进,它可以用有损压缩方式去除冗余的图像数据,就是可以用较少的磁盘空间得到较好的图像品质。而且JPEG是一种很灵活的格式,具有调节图像质量的功能,它允许用不同的压缩比例对文件进行压缩,支持多种压缩级别,压缩比率通常在10;1到40;1,压缩比越大,图像品质就越低;相反地,压缩比越小,图像品质就越高。同一幅图像,用JPEG格式存储的文件是其他类型文件的1/10~1/20,通常只有几十KB,质量损失较小,基本无法看出。JPEG格式压缩的主要是高频信息,对色彩的信息保留较好,适合应用于互联网;它可减少图像的传输时间,支持24位真彩色;也普遍应用于需要连续色调的图像中。
JPEG编码器系统框图:
2.JPEG文件格式分析
JPEG文件以segment的形式组织,其中每个segment以一个marker开始,而每个marker均以0xFF和一个marker的标识符开始,随后为2字节的marker长度(不包含marker的起始两字节)和对应的payload(SOI和EOI marker只有2字节的标识符)。连续的0xFF字节并不是marker的起始标志,而是用来填充的特殊字符。此外,0xFF后若为0x00,则跳过此字节不予处理。
概括来说,一共有以下几种字段:
根据实验所给的《JPEG解码调试报告》可以理解:
1)SOI、EOI:
FFD8: SOI,Start of Image,图像开始;所有的 JPEG 文件必须以 SOI 开始。
FFD9: End of Image,图像结束;结束符,JPEG 文件必须以 EOI 结束。
2)APP0:
FFE0: APP0,Application,应用程序保留标记 0;length: 16 byte (2 byte)00 10 4A 46 49 46 00 01 01 01 00 48 00 48 00 00 ;标识符: JFIF (5 byte);Version: 2 byte;Units: 1 byte X and Y are dots per inch;Xdensity: 2 bytes Horizontal pixel density(水平方向点密度);Ydensity: 2 bytes Vertical pixel density(垂直方向点密度);缩略图水平像素数目: 1 byte;缩略图垂直像素数目: 1 byte;缩略图 24bitRGB 点数目: 缩略图水平像素数目 * 缩略图垂直像素数目 = 1 byte
3)DQT:
量化表标记代码:FFDB量化表长度:(17byte),长度本身占 2 字节,精度及量化表 ID:1byte, 低位为量化表的 ID 的索引值,其取值范围为 0~3,所以说最多可能有四张量化表(亮度量化表,色度量化表,可能会有 R、G、B 各一张量化表);而低位为量化精度,有两个可选值,0:8 位;1:16 位,这里是 00,代表量化精度为 8bit,即用一个字节来表示一个量化系数数据:64 字节的量化系数,(一个字节对应一个量化系数,对于 88 的宏块来说,共 88=64 个量化系数)
4)SOF0:
SOF0: start of frame,帧图像开始;数据长度:长度本身占 2byte;图像精度: 1byte, 若是 08,即精度为一个字节。图像高度:2 byte, 以像素为单位。图像宽度:2 byte, 以像素为单位。颜色分量数:一个字节,这里是 03,代表有三个分量,YCrCb。颜色分量信息:每个分量有三个字节,第一个为分量的 ID,01:Y 02:U 03:V ;第二个字节高位为水平采样因子,低位为垂直采样因子,这里三个分量的采样率相同,所以采样格式为 4:4:4;第三个字节代表这个分量对应的量化表 ID,可以看出,Y 对应的量化表 ID 索引值为 00,而 UV 对应的量化表 ID都为 01,即它们共用一张量化表。
5)DHT:
FFC4:标记代码,2 字节,代表定义 Huffman 表。数据长度: 2 字节 这里是 28 字节的长度(包括长度自身);Huffman 表 ID 号和类型:1 字节,高 4 位为表的类型,0:DC 直流;1:AC交流 可以看出这里是直流表;低四位为 Huffman 表 ID。可以看出这张表是直流 DC 的第 0 张表,在后面的扫描开始的部分中我们可以获右为亮度的直流系数表。不同长度 Huffman 的码字数量:固定为 16 个字节,每个字节代表从长度为 1到长度为 16 的 码 字 的个 数 , 以 表 中 的 分析, 这 16 个字节之后的2+3+1+1+1+1=9 个字节对应的就是每个符字对应的权值,这些权值的含义即为 DC 系数经 DPCM 编码后幅度值的位长。通过码长与码字个数的关系来生成相应码长的码字,再对应上之后的权值即位长根据解码得到的位长来读取之后相应长度的码字,再查可变长二进制编码表,就可以得到直流系数的幅度值,注意这个幅度值是经过 DPCM 差分编码得到的。
6)SOS
FFDA: 标记代码 SOS,Start of Scan,扫描开始 数据长度:2 字节。颜色分量数:1 字节 ,应该和 SOF 中的颜色分量数相同;颜色分量信息:每个分量对应 3 个字节,第一个字节是颜色分量 ID,1,2,3对应 YUV,第二个字节高位为直流分量使用的哈夫曼树编号。压缩图像数据 a)谱选择开始 1 字节 固定值 0x00;b)谱选择结束 1 字节 固定值 0x3F;c)谱选择 1 字节 在基本 JPEG 中总为 00 。
三、实验步骤
1.理解程序设计整体框架
int convert_one_image(const char *infilename, const char *outfilename, int output_format)//解码函数
{
FILE *fp;
unsigned int length_of_file;//文件的大小
unsigned int width, height;//定义图像的宽和高
unsigned char *buf;//设buf缓冲区
struct jdec_private *jdec;
unsigned char *components[3];
/* 将.jpg文件读入buf中 */
fp = fopen(infilename, "rb");//打开输入文件
if (fp == NULL)
exitmessage("Cannot open filename\n");
length_of_file = filesize(fp);
buf = (unsigned char *)malloc(length_of_file + 4);
if (buf == NULL)
exitmessage("Not enough memory for loading file\n");
fread(buf, length_of_file, 1, fp);
fclose(fp);
/* Decompress it */
jdec = tinyjpeg_init();//初始化
if (jdec == NULL)
exitmessage("Not enough memory to alloc the structure need for decompressing\n");
if (tinyjpeg_parse_header(jdec, buf, length_of_file)<0)//解析.jpg文件头
exitmessage(tinyjpeg_get_errorstring(jdec));
/* Get the size of the image */
tinyjpeg_get_size(jdec, &width, &height);//算.jpg文件的宽高
snprintf(error_string, sizeof(error_string),"Decoding JPEG image...\n");
if (tinyjpeg_decode(jdec, output_format) < 0)//解码实际数据
exitmessage(tinyjpeg_get_errorstring(jdec));
/*
* Get address for each plane (not only max 3 planes is supported), and
* depending of the output mode, only some components will be filled
* RGB: 1 plane, YUV420P: 3 planes, GREY: 1 plane
*/
tinyjpeg_get_components(jdec, components);
/* 按照指定的文件输出格式保存输出文件 */
switch (output_format)
{
case TINYJPEG_FMT_RGB24:
case TINYJPEG_FMT_BGR24:
write_tga(outfilename, output_format, width, height, components);
break;
case TINYJPEG_FMT_YUV420P:
write_yuv(outfilename, width, height, components);
break;
case TINYJPEG_FMT_GREY:
write_pgm(outfilename, width, height, components);
break;
}
/* Only called this if the buffers were allocated by tinyjpeg_decode() */
tinyjpeg_free(jdec);
/* else called just free(jdec); */
free(buf);
return 0;
}
1.解析Segment Marker
1.1解析文件头:
在tinyjpeg_parse_header中,解析JPEG的文件头。
int tinyjpeg_parse_header(struct jdec_private *priv, const unsigned char *buf, unsigned int size)//解析JPEG文件头
{
int ret;
/* Identify the file */
if ((buf[0] != 0xFF) || (buf[1] != SOI))
snprintf(error_string, sizeof(error_string),"Not a JPG file ?\n");
priv->stream_begin = buf+2;
priv->stream_length = size-2;
priv->stream_end = priv->stream_begin + priv->stream_length;
ret = parse_JFIF(priv, priv->stream_begin);//开始解析
return ret;
}
解析APP0:解析 APP0: 检查标识“ JFIF”及版本,得到一些参数。
解析 DQT: 得到量化表长度(可能包含多张量化表);得到量化表的精度;得到及检查量化表的序号(只能是 0 ~3);得到量化表内容(64 个数据)。
解析 SOF0:得到每个 sample 的比特数、长宽、颜色分量数
得到每个颜色分量的 ID、水平采样因子、垂直采样因子、使用的量化表序号(与 DQT 中序号对应)。
解析 DHT: 得到 Huffman 表的类型(AC、DC)序号,依据数据重建 Huffman 表。
解析 SOS: 得到解析每个颜色分量的 DC、AC 值所使用的 Huffman 表序号。
依据每个分量的水平、垂直采样因子计算 MCU 的大小,并得到每个 MCU 中 8*8 宏块的个数
对每个 MCU 解码(依照各分量水平、垂直采样因子对 MCU 中每个分量宏块解码);对每个宏块进行 Huffman 解码;解码 DC 差值,重构量化后的系数;DCT 逆变换;丢弃填充的行/列;反 0 偏置。
遇到 Segment Marker RST 时,清空之前的 DC DCT 系数。
解析到 EOI,解码结束
将 Y、 Cb、 Cr 转化为需要的色彩空间并保存。
2.理解三个结构体的设计目的
struct huffman_table
目的:用于存储所有用到的哈夫曼码表
struct huffman_table
{
/* Fast look up table, using HUFFMAN_HASH_NBITS bits we can have directly the symbol,
* if the symbol is <0, then we need to look into the tree table */
short int lookup[HUFFMAN_HASH_SIZE];
/* code size: give the number of bits of a symbol is encoded */
unsigned char code_size[HUFFMAN_HASH_SIZE];
/* some place to store value that is not encoded in the lookup table
* FIXME: Calculate if 256 value is enough to store all values
*/
uint16_t slowtable[16-HUFFMAN_HASH_NBITS][256];
};
struct component
用于储存当前8×8像块中有关解码的信息,参与霍夫曼解码,反量化,IDCT 以及彩色空间变换。
Hfactor和 Vfactor 用于说明水平与垂直的采样情况。
struct component
{
unsigned int Hfactor;//水平采样
unsigned int Vfactor;//垂直采样
float *Q_table; /* Pointer to the quantisation table to use */
struct huffman_table *AC_table;//指向AC分量进行解码时所需的码表
struct huffman_table *DC_table;//指向DC分量进行解码时所需的码表
short int previous_DC; /* Previous DC coefficient */
short int DCT[64]; /* DCT 系数矩阵*/
#if SANITY_CHECK
unsigned int cid;
#endif
};
struct jdec_private
码流结构体,包含了所有完整的内容的定义,用于存储JPEG图像宽高、数据流指针、Huffman码表、图像数据等内容。
struct jdec_private
{
/* Public variables */
uint8_t *components[COMPONENTS];
unsigned int width, height; /* Size of the image */
unsigned int flags;
/* Private variables */
const unsigned char *stream_begin, *stream_end;
unsigned int stream_length;
const unsigned char *stream; /* Pointer to the current stream */
unsigned int reservoir, nbits_in_reservoir;
struct component component_infos[COMPONENTS];
float Q_tables[COMPONENTS][64]; /* quantization tables */
struct huffman_table HTDC[HUFFMAN_TABLES]; /* DC huffman tables */
struct huffman_table HTAC[HUFFMAN_TABLES]; /* AC huffman tables */
int default_huffman_table_initialized;
int restart_interval;
int restarts_to_go; /* MCUs left in this restart interval */
int last_rst_marker_seen; /* Rst marker is incremented each time */
/* Temp space used after the IDCT to store each components */
uint8_t Y[64*4], Cr[64], Cb[64];
jmp_buf jump_state;
/* Internal Pointer use for colorspace conversion, do not modify it !!! */
uint8_t *plane[COMPONENTS];
};
3.理解在视音频编解码调试中TRACE的目的和含义
含义:TRACE相当于一个开关,设为1时,则打开TRACE,正常运行里面的程序,设为0时,相当于关闭TRACE,则直接跳过TRACE里的程序。
目的:通过获取一些调试信息,来协助程序的调试。
#if TRACE//开关,可以打开
p_trace=fopen(TRACEFILE,"w");
if (p_trace==NULL)
{
printf("trace file open error!");
}
#endif
四、实验结果
1.输出yuv文件
static void write_yuv(const char *filename, int width, int height, unsigned char **components)
{
FILE *F;
char temp[1024];
snprintf(temp, 1024, "%s.Y", filename);
F = fopen(temp, "wb");
fwrite(components[0], width, height, F);
fclose(F);
snprintf(temp, 1024, "%s.U", filename);
F = fopen(temp, "wb");
fwrite(components[1], width*height/4, 1, F);
fclose(F);
snprintf(temp, 1024, "%s.V", filename);
F = fopen(temp, "wb");
fwrite(components[2], width*height/4, 1, F);
fclose(F);
snprintf(temp, 1024, "%s.YUV", filename);//将字符串赋给temp,即temp=filename.yuv
F = fopen(temp, "wb");
fwrite(components[0], width*height, 1, F);//该文件先把components[0]往里开始写,再往里写components[1],再往里写component[2]。(先写ybuffer再写ubuffer再写vbuffer)
fwrite(components[1], width*height/4, 1, F);
fwrite(components[2], width*height/4, 1, F);
fclose(F);
}
2. 以txt文件输出所有的量化矩阵和所有的HUFFMAN码表
static void build_quantization_table(float *qtable, const unsigned char *ref_table)
{
/* Taken from libjpeg. Copyright Independent JPEG Group's LLM idct.
* For float AA&N IDCT method, divisors are equal to quantization
* coefficients scaled by scalefactor[row]*scalefactor[col], where
* scalefactor[0] = 1
* scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
* We apply a further scale factor of 8.
* What's actually stored is 1/divisor so that the inner loop can
* use a multiplication rather than a division.
*/
int i, j;
static const double aanscalefactor[8] = {
1.0, 1.387039845, 1.306562965, 1.175875602,
1.0, 0.785694958, 0.541196100, 0.275899379
};
const unsigned char *zz = zigzag;
for (i=0; i<8; i++) {
for (j=0; j<8; j++) {
*qtable++ = ref_table[*zz++] * aanscalefactor[i] * aanscalefactor[j];
fprintf(p_trace,"%-6d ",ref_table[*zz++]);//输出ref_table
if (j == 7) {
fprintf(p_trace, "\n");}
}
}
}
static void build_huffman_table(const unsigned char *bits, const unsigned char *vals, struct huffman_table *table)
{
unsigned int i, j, code, code_size, val, nbits;
unsigned char huffsize[HUFFMAN_BITS_SIZE+1], *hz;
unsigned int huffcode[HUFFMAN_BITS_SIZE+1], *hc;
int next_free_entry;
/*
* Build a temp array
* huffsize[X] => numbers of bits to write vals[X]
*/
hz = huffsize;
for (i=1; i<=16; i++)
{
for (j=1; j<=bits[i]; j++)
*hz++ = i;
}
*hz = 0;
memset(table->lookup, 0xff, sizeof(table->lookup));
for (i=0; i<(16-HUFFMAN_HASH_NBITS); i++)
table->slowtable[i][0] = 0;
/* Build a temp array
* huffcode[X] => code used to write vals[X]
*/
code = 0;
hc = huffcode;
hz = huffsize;
nbits = *hz;
while (*hz)
{
while (*hz == nbits)
{
*hc++ = code++;
hz++;
}
code <<= 1;
nbits++;
}
/*
* Build the lookup table, and the slowtable if needed.
*/
next_free_entry = -1;
for (i=0; huffsize[i]; i++)
{
val = vals[i];
code = huffcode[i];
code_size = huffsize[i];
#if TRACE
fprintf(p_trace,"val=%2.2x code=%8.8x codesize=%2.2d\n", val, code, code_size);
fflush(p_trace);
#endif
table->code_size[val] = code_size;
if (code_size <= HUFFMAN_HASH_NBITS)
{
/*
* Good: val can be put in the lookup table, so fill all value of this
* column with value val
*/
int repeat = 1UL<<(HUFFMAN_HASH_NBITS - code_size);
code <<= HUFFMAN_HASH_NBITS - code_size;
while ( repeat-- )
table->lookup[code++] = val;
}
else
{
/* Perhaps sorting the array will be an optimization */
uint16_t *slowtable = table->slowtable[code_size-HUFFMAN_HASH_NBITS-1];
while(slowtable[0])
slowtable+=2;
slowtable[0] = code;
slowtable[1] = val;
slowtable[2] = 0;
/* TODO: NEED TO CHECK FOR AN OVERFLOW OF THE TABLE */
}
}
}