使用C++实现LZW 编解码算法(更新过)
一、LZW算法是什么?
1、LZW算法简介
LZW算法又叫“串表压缩算法”就是通过建立一个字符串表,用较短的代码来表示较长的字符串来实现压缩。
字符串和编码的对应关系是在压缩过程中动态生成的,并且隐含在压缩数据中,解压的时候根据表来进行恢复,算是一种无损压缩.
LZW压缩算法的基本原理:提取原始文本文件数据中的不同字符,基于这些字符创建一个编译表,然后用编译表中的字符的索引来替代原始文本文件数据中的相应字符,减少原始数据大小。看起来和调色板图象的实现原理差不多,但是应该注意到的是,我们这里的编译表不是事先创建好的,而是根据原始文件数据动态创建的,解码时还要从已编码的数据中还原出原来的编译表.
2、简易流程图
简易流程图如下:
3、LZW压缩的特点
LZW码能有效利用字符出现频率冗余度进行压缩,且字典是自适应生成的,但通常不能有效地利用位置冗余度。
具体特点如下:
l)LZW压缩技术对于可预测性不大的数据具有较好的处理效果,常用于TIF格式的图像压缩,其平均压缩比在2:1以上,最高压缩比可达到3:1。
2)对于数据流中连续重复出现的字节和字串,LZW压缩技术具有很高的压缩比。
3)除了用于图像数据处理以外,LZW压缩技术还被用于文本程序等数据压缩领域。
4)LZW压缩技术有很多变体,例如常见的ARC、RKARC、PKZIP高效压缩程序。
5)对于任意宽度和像素位长度的图像,都具有稳定的压缩过程。压缩和解压缩速度较快。
6)对机器硬件条件要求不高,在 Intel 80386的计算机上即可进行压缩和解压缩。
二、使用C++实现LZW 编解码算法
1、逻辑结构分析
字典存储的逻辑结构是Trie树。这种树是动态增长的。
树是动态建立的,且树中每个节点可能存在多个子节点。因此数据结构应该设计成一个节点可拥有任意个子节点,但无需为其预留空间从根节点不断往下扩充,对应新的字符串。
每当我们要找一个字符串,从树的叶子节点往上溯源到祖先节点,我们就可以找出我们要的字符串。
2、使用C++实现LZW编码
LZW的编码思想是不断地从字符流中提取新的字符串,通俗地理解为新“词条”,然后用“代号”也就是码字表示这个“词条”。这样一来,对字符流的编码就变成了用码字去替换字符流,生成码字流,从而达到压缩数据的目的。LZW编码是围绕称为词典的转换表来完成的。LZW编码器通过管理这个词典完成输入与输出之间的转换。LZW编码器的输入是字符流,字符流可以是用8位ASCII字符组成的字符串,而输出是用n位(例如12位)表示的码字流。LZW编码算法的步骤如下:
步骤1:将词典初始化为包含所有可能的单字符,当前前缀P初始化为空。
步骤2:当前字符C=字符流中的下一个字符。
步骤3:判断P+C是否在词典中
(1)如果“是”,则用C扩展P,即让P=P+C,返回到步骤2。
(2)如果“否”,则
输出与当前前缀P相对应的码字W;
将P+C添加到词典中;
令P=C,并返回到步骤2
LZW编码算法可用下述函数实现。首先初始化词典,然后顺序从待压缩文件中读入字符并按照上述算法执行编码。最后将编得的码字流输出至文件中。
//LZW编码
void LZWEncode(FILE* fp, BITFILE* bf) {
int character;
int string_code;
int index;
unsigned long file_length;
fseek(fp, 0, SEEK_END);
file_length = ftell(fp);//使用seek指针计算文件长度
fseek(fp, 0, SEEK_SET);//返回开头
BitsOutput(bf, file_length, 4 * 8);
InitDictionary();
string_code = -1;//设置字符或字符串所对应的词典编码为-1
while (EOF != (character = fgetc(fp))) {//当不是EOF时从文件里读取字符
index = InDictionary(character, string_code); //这个字符串是否在字典里
if (0 <= index) { // string+character in dictionary
string_code = index;
}
else { // string+character not in dictionary
output(bf, string_code);
if (MAX_CODE > next_code) { // free space in dictionary
// add string+character to dictionary
AddToDictionary(character, string_code);//将新词条加入词典
}
string_code = character;//将目前字符的代号放入前缀
}
}
output(bf, string_code);
}
3、使用C++实现LZW解码
LZW解码算法开始时,译码词典和编码词典相同,包含所有可能的前缀根。具体解码算法如下:
步骤1:在开始译码时词典包含所有可能的前缀根。
步骤2:令CW:=码字流中的第一个码字。
步骤3:输出当前缀-符串string.CW到码字流。
步骤4:先前码字PW:=当前码字CW。
步骤5:当前码字CW:=码字流的下一个码字。
步骤6:判断当前缀-符串string.CW 是否在词典中。
(1)如果”是”,则把当前缀-符串string.CW输出到字符流。
当前前缀P:=先前缀-符串string.PW。
当前字符C:=当前前缀-符串string.CW的第一个字符。
把缀-符串P+C添加到词典。
(2)如果”否”,则当前前缀P:=先前缀-符串string.PW。
当前字符C:=当前缀-符串string.CW的第一个字符。
输出缀-符串P+C到字符流,然后把它添加到词典中。
步骤7:判断码字流中是否还有码字要译。
(1)如果”是”,就返回步骤4。
(2)如果”否”,结束。
LZW解码算法可用下述函数实现。首先初始化词典,然后顺序从压缩文件中读入码
字并按照上述算法执行解码。最后将解得的字符串输出至文件中。
//LZW解码
void LZWDecode(BITFILE* bf, FILE* fp) {
int character;
int new_code, last_code;
int phrase_length;
unsigned long file_length;
file_length = BitsInput(bf, 4 * 8);//计算有多少个字符
if (-1 == file_length) file_length = 0;
/*需填充*/
InitDictionary();//初始化词典
last_code = -1;
while (0 < file_length) {
new_code = input(bf);//读入一个代号
if (new_code >= next_code) { // this is the case CSCSC( not in dict)
d_stack[0] = character;// 当前字符代号先记录在栈里
phrase_length = DecodeString(1, last_code);//解出字符,存入d_stack栈里
}
else {
phrase_length = DecodeString(0, new_code);//解出字符,存入d_stack栈里
}
character = d_stack[phrase_length - 1];// 更新下一个字符为当前字符串首字符
while (0 < phrase_length) {//输出字符串到文件中
phrase_length--;
fputc(d_stack[phrase_length], fp);
file_length--;
}
if (MAX_CODE > next_code) {//如果字典大于词条 add the new phrase to dictionary
AddToDictionary(character, last_code);//将字符加入到字典中
}
last_code = new_code;//更新字典条数last_code为new_code
}
}
4、完整代码
/*
* Definition for LZW coding
*
* vim: ts=4 sw=4 cindent nowrap
*/
#include <stdlib.h>
#include <stdio.h>
#include "bitio.h"
#define MAX_CODE 65535
#pragma warning(disable:4996)
struct {
int suffix;
int parent, firstchild, nextsibling;
} dictionary[MAX_CODE + 1];
int next_code;
int d_stack[MAX_CODE]; // stack for decoding a phrase
#define input(f) ((int)BitsInput( f, 16))
#define output(f, x) BitsOutput( f, (unsigned long)(x), 16)
int DecodeString(int start, int code);
void InitDictionary(void);
//输出字典
void PrintDictionary(void) {
int n;
int count;
for (n = 256; n < next_code; n++) {
count = DecodeString(0, n);
printf("%4d->", n);
while (0 < count--) printf("%c", (char)(d_stack[count]));
printf("\n");
}
}
int DecodeString(int start, int code) {
int count;//记录当前字符串长度
count = start;//定义开始时刻,从start开始
while (0 <= code) {
d_stack[count] = dictionary[code].suffix;//将字符串的尾缀放入栈
code = dictionary[code].parent;//回到父节点
count++;//字符串长度计数+1
}
return count;
}
void InitDictionary(void) {
int i;
for (i = 0; i < 256; i++) {
dictionary[i].suffix = i;//尾缀字符
dictionary[i].parent = -1;//父节点
dictionary[i].firstchild = -1;//第一个孩子节点
dictionary[i].nextsibling = i + 1;//下一个兄弟结点
}
dictionary[255].nextsibling = -1;
next_code = 256;
}
/*
* Input: string represented by string_code in dictionary,
* Output: the index of character+string in the dictionary
* index = -1 if not found
*/
int InDictionary(int character, int string_code) {
int sibling;
if (0 > string_code) return character;
sibling = dictionary[string_code].firstchild;
while (-1 < sibling) {
if (character == dictionary[sibling].suffix) return sibling;
sibling = dictionary[sibling].nextsibling;
}
return -1;
}
//将新词条放入词典
void AddToDictionary(int character, int string_code) {
int firstsibling, nextsibling;
if (0 > string_code) return;
dictionary[next_code].suffix = character;
dictionary[next_code].parent = string_code;
dictionary[next_code].nextsibling = -1;
dictionary[next_code].firstchild = -1;
firstsibling = dictionary[string_code].firstchild;
if (-1 < firstsibling) { // the parent has child
nextsibling = firstsibling;
while (-1 < dictionary[nextsibling].nextsibling)
nextsibling = dictionary[nextsibling].nextsibling;
dictionary[nextsibling].nextsibling = next_code;
}
else {// no child before, modify it to be the first
dictionary[string_code].firstchild = next_code;
}
next_code++;
}
//LZW编码
void LZWEncode(FILE* fp, BITFILE* bf) {
int character;
int string_code;
int index;
unsigned long file_length;
fseek(fp, 0, SEEK_END);
file_length = ftell(fp);//使用seek指针计算文件长度
fseek(fp, 0, SEEK_SET);//返回开头
BitsOutput(bf, file_length, 4 * 8);
InitDictionary();
string_code = -1;//设置字符或字符串所对应的词典编码为-1
while (EOF != (character = fgetc(fp))) {//当不是EOF时从文件里读取字符
index = InDictionary(character, string_code); //这个字符串是否在字典里
if (0 <= index) { // string+character in dictionary
string_code = index;
}
else { // string+character not in dictionary
output(bf, string_code);
if (MAX_CODE > next_code) { // free space in dictionary
// add string+character to dictionary
AddToDictionary(character, string_code);//将新词条加入词典
}
string_code = character;//将目前字符的代号放入前缀
}
}
output(bf, string_code);
}
//LZW解码
void LZWDecode(BITFILE* bf, FILE* fp) {
int character;
int new_code, last_code;
int phrase_length;
unsigned long file_length;
file_length = BitsInput(bf, 4 * 8);//计算有多少个字符
if (-1 == file_length) file_length = 0;
/*需填充*/
InitDictionary();//初始化词典
last_code = -1;
while (0 < file_length) {
new_code = input(bf);//读入一个代号
if (new_code >= next_code) { // this is the case CSCSC( not in dict)
d_stack[0] = character;// 当前字符代号先记录在栈里
phrase_length = DecodeString(1, last_code);//解出字符,存入d_stack栈里
}
else {
phrase_length = DecodeString(0, new_code);//解出字符,存入d_stack栈里
}
character = d_stack[phrase_length - 1];// 更新下一个字符为当前字符串首字符
while (0 < phrase_length) {//输出字符串到文件中
phrase_length--;
fputc(d_stack[phrase_length], fp);
file_length--;
}
if (MAX_CODE > next_code) {//如果字典大于词条 add the new phrase to dictionary
AddToDictionary(character, last_code);//将字符加入到字典中
}
last_code = new_code;//更新字典条数last_code为new_code
}
}
int main(int argc, char** argv) {
FILE* fp;
BITFILE* bf;
if (4 > argc) {
fprintf(stdout, "usage: \n%s <o> <ifile> <ofile>\n", argv[0]);
fprintf(stdout, "\t<o>: E or D reffers encode or decode\n");
fprintf(stdout, "\t<ifile>: input file name\n");
fprintf(stdout, "\t<ofile>: output file name\n");
return -1;
}
if ('E' == argv[1][0]) { // do encoding
fp = fopen(argv[2], "rb");
bf = OpenBitFileOutput(argv[3]);
if (NULL != fp && NULL != bf) {
LZWEncode(fp, bf);
fclose(fp);
CloseBitFileOutput(bf);
fprintf(stdout, "encoding done\n");
}
}
else if ('D' == argv[1][0]) { // do decoding
bf = OpenBitFileInput(argv[2]);
fp = fopen(argv[3], "wb");
if (NULL != fp && NULL != bf) {
LZWDecode(bf, fp);
fclose(fp);
CloseBitFileInput(bf);
fprintf(stdout, "decoding done\n");
}
}
else { // otherwise
fprintf(stderr, "not supported operation\n");
}
return 0;
}
5、结果
通过对比发现,原文件与解压后文件内容一样,说明代码运行正确,实现目标
三、压缩效率分析
1、.txt文件的压缩效率分析
重复率极高的原来文本内容:
压缩前后对比:
对比可发现,压缩后大小变小,压缩效率小于1
但如果将.txt文件中的输入值变混乱,如下图
压缩前后对比:
对比可发现,压缩后大小变大,压缩效率大于1,可知,当重复率较低的时候,LZW压缩并不能很好的发挥作用。
2、.jpeg文件的压缩效率分析
图片压缩前后对比如下:
同时也对其他5张.jpeg格式文件进行压缩,通过对比发现,压缩后文件大小变大,压缩效率大于1
3、对其他格式进行比较
通过比较.mp4,.bmp,.mkv,.avi等多个格式发现,只有txt和bmp出现压缩后文件大小变小的情况,且变小的效率也不是很大,多数文件都出现压缩后文件大小反而增加的情况。说明LZW算法在一定情况下一定程度上完成对文件的压缩,尤其是对于数据流中连续重复出现的字节和字串,LZW压缩技术具有很高的压缩比。但其可能不太能适合对视频等重复程度较小的文件的压缩。
四、当前码字在词典中不存在时应如何处理并解释原因。
出现次情况原因:编码时,上一个新的词条刚被创建,紧接着下一个词条就需要使用它。并且因为解码端的解码会比编码端晚一步,所以我们没有得到最新的词条,就需要使用它,就会出现当前码字在词典中不存在的情况。
处理办法:因为出现这种情况的时候每个词条的首尾必定是相同的,因此获取到上一个码字所代表的词条,然后将该词条的第一个字符加到该词条的尾部,这样就形成了一个新的词条,该词条也就是那一个码字不在词典中的码字所对应的词条。再将这个码字和对应的词条写入字典中即可。
五、归纳总结
通过此次实验进一步了解LZW格式,并实现了LZW编码与解码的过程。同时,经过详细分析压缩后与源文件的文件大小,了解LZW的压缩效率。并且熟悉巩固了C++语言的使用,为后续进一步学习数据压缩打下了基础。