LZW算法原理及实现

LZW算法原理及实现

LZW算法原理

LZW属于第二类词典编码,其基本思想是:企图从输入的数据中创建一个“短语词典”,这种短语词典可以是任意字符的组合。编码数据过程中,当遇到已经在字典中出现的“短语”时,编码器就输出这个词典中的短语的“索引号”,而不是短语本身。

LZW编码过程

编码的流程大致如下:

步骤1:将词典初始化为包含所有可能的单字符,当前前缀P初始化为空。

步骤2:当前字符C = 字符流中的下一个字符

步骤3:判断P+C是否在词典中:

  • 如果“是”,则用C扩展P,即让P = P+C,返回到步骤2。

  • 如果“否”,则输出与当前前缀P相对应的码字W并将P+C添加到词典中,
    令P = C,并返回到步骤2。

LZW解码过程

解码的流程大致如下:

步骤1:在开始译码时词典包含所有可能的前缀根

步骤2:令CW=码字流中的第一个码字

步骤3:输出当前字符串CW到码字流。

步骤4:先前码字PW=当前码字CW。

步骤5:当前码字CW=码字流的下一个码字。

步骤6:判断当前字符串CW是否在词典中。

如果”是”,则把当前字符串CW输出到字符流。

  • 当前前缀P = PW。
  • 当前字符C=当前字符串的第一个字符。
  • 把P + C添加到词典。
  • PW = CW

如果”否”,则当前前缀P = PW。

  • 当前字符C=先前字符串PW的第一个字符。
  • 输出P + C到字符流,然后把它添加到词典中。
  • PW = CW

实验过程实现

位输入输出工具

由于索引号会产生大于255的情况,所以1byte肯定是不够的,但如果直接开到int又会造成资源浪费,所以我们需要根据实际的字典大小来确定位数,这就需要按位输入输出工具了:

/*
 * Declaration for bitwise IO
 *
 * vim: ts=4 sw=4 cindent
 */
#ifndef __BITIO__
#define __BITIO__

#include <stdio.h>

typedef struct{
	FILE *fp;
	unsigned char mask;
	int rack;
}BITFILE;

BITFILE *OpenBitFileInput( char *filename);
BITFILE *OpenBitFileOutput( char *filename);
void CloseBitFileInput( BITFILE *bf);
void CloseBitFileOutput( BITFILE *bf);
int BitInput( BITFILE *bf);
unsigned long BitsInput( BITFILE *bf, int count);
void BitOutput( BITFILE *bf, int bit);
void BitsOutput( BITFILE *bf, unsigned long code, int count);
#endif	// __BITIO__

函数实现如下:

/*
 * Definitions for bitwise IO
 *
 * vim: ts=4 sw=4 cindent
 */

#include <stdlib.h>
#include <stdio.h>
#include "bitio.h"
BITFILE *OpenBitFileInput( char *filename){
	BITFILE *bf;
	bf = (BITFILE *)malloc( sizeof(BITFILE));
	if( NULL == bf) return NULL;
	if( NULL == filename)	bf->fp = stdin;
	else bf->fp = fopen( filename, "rb");
	if( NULL == bf->fp) return NULL;
	bf->mask = 0x80;
	bf->rack = 0;
	return bf;
}

BITFILE *OpenBitFileOutput( char *filename){
	BITFILE *bf;
	bf = (BITFILE *)malloc( sizeof(BITFILE));
	if( NULL == bf) return NULL;
	if( NULL == filename)	bf->fp = stdout;
	else bf->fp = fopen( filename, "wb");
	if( NULL == bf->fp) return NULL;
	bf->mask = 0x80;
	bf->rack = 0;
	return bf;
}

void CloseBitFileInput( BITFILE *bf){
	fclose( bf->fp);
	free( bf);
}

void CloseBitFileOutput( BITFILE *bf){
	// Output the remaining bits
	if( 0x80 != bf->mask) fputc( bf->rack, bf->fp);
	fclose( bf->fp);
	free( bf);
}

int BitInput( BITFILE *bf){
	int value;
	if( 0x80 == bf->mask){
		bf->rack = fgetc( bf->fp);
		if( EOF == bf->rack){
			fprintf(stderr, "Read after the end of file reached\n");
			exit( -1);
		}
	}
	value = bf->mask & bf->rack;
	bf->mask >>= 1;
	if( 0==bf->mask) bf->mask = 0x80;
	return( (0==value)?0:1);
}

unsigned long BitsInput( BITFILE *bf, int count){
	unsigned long mask;
	unsigned long value;
	mask = 1L << (count-1);
	value = 0L;
	while( 0!=mask){
		if( 1 == BitInput( bf))
			value |= mask;
		mask >>= 1;
	}
	return value;
}

void BitOutput( BITFILE *bf, int bit){
	if( 0 != bit) bf->rack |= bf->mask;
	bf->mask >>= 1;
	if( 0 == bf->mask){	// eight bits in rack
		fputc( bf->rack, bf->fp);
		bf->rack = 0;
		bf->mask = 0x80;
	}
}

void BitsOutput( BITFILE *bf, unsigned long code, int count){
	unsigned long mask;

	mask = 1L << (count-1);
	while( 0 != mask){
		BitOutput( bf, (int)(0==(code&mask)?0:1));
		mask >>= 1;
	}
}
#if 0
int main( int argc, char **argv){
	BITFILE *bfi, *bfo;
	int bit;
	int count = 0;

	if( 1<argc){
		if( NULL==OpenBitFileInput( bfi, argv[1])){
			fprintf( stderr, "fail open the file\n");
			return -1;
		}
	}else{
		if( NULL==OpenBitFileInput( bfi, NULL)){
			fprintf( stderr, "fail open stdin\n");
			return -2;
		}
	}
	if( 2<argc){
		if( NULL==OpenBitFileOutput( bfo, argv[2])){
			fprintf( stderr, "fail open file for output\n");
			return -3;
		}
	}else{
		if( NULL==OpenBitFileOutput( bfo, NULL)){
			fprintf( stderr, "fail open stdout\n");
			return -4;
		}
	}
	while( 1){
		bit = BitInput( bfi);
		fprintf( stderr, "%d", bit);
		count ++;
		if( 0==(count&7))fprintf( stderr, " ");
		BitOutput( bfo, bit);
	}
	return 0;
}
#endif

编解码

我们使用Trie树来构建编解码所需要的词典,但是需要注意的是:编码器端是从根节点开始构建一棵树,但是在解码端却是从叶子节点开始回退到根节点上,这里的顺序会影响我们后续代码的编写:

/*
 * Definition for LZW coding 
 *
 * vim: ts=4 sw=4 cindent nowrap
 */
#include <stdlib.h>
#include <stdio.h>
#include "bitio.h"
#define MAX_CODE 65535

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; 
	while (0 <= code) {
		d_stack[count] = dictionary[code].suffix;
		code = dictionary[code].parent; // 回退到父节点节点
		count++;
	}
	return count;
}

void InitDictionary(void){
	int i;
	for( i=0; i<256; i++){   //将ASCII中的字符加入到字典中
		dictionary[i].suffix = i;   // 初始化单个字符
		dictionary[i].parent = -1;  // 对于单个字符而言,他们的父节点是空(-1)
		dictionary[i].firstchild = -1; // 对于一开始初始化的节点,他们的孩子节点也是空的
		dictionary[i].nextsibling = i+1;  // 但是所有的单个字符都是属于一个父亲节点
	}
	dictionary[255].nextsibling = -1;  // 最后一个节点没有兄弟
	next_code = 256;  // 下一个加入词典的节点序号为next_code
}
/*
 * 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){  // character是当前字符,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;  // 没有查找到,返回-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 ++; 
}

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);
	fseek( fp, 0, SEEK_SET);
	BitsOutput( bf, file_length, 4*8);
	InitDictionary();
	string_code = -1;
	while(EOF!=(character=fgetc(fp))){  // 一次读取一个字符
		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);  // 最后一定要输出一次!
}

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){ // 不存在这个字串,说明我们在编码端出现了这样的情况:刚加入词典的字串在下一次编码时接着被用到了!
            d_stack[0] = character;  // 此时需要用前一个字串的第一个字符
            phrase_length = DecodeString(1, last_code);  // 此时d_stack[0]已经占用了,所以需要从1开始解码前一个字串
        }
        else{
            phrase_length = DecodeString(0, new_code);  // 获得这个字串
        }
        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;
    }
}

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

实验结果

对于单个Txt文件

将如下的txt文件进行处理:
在这里插入图片描述
代码跑出来的结果如下:
在这里插入图片描述
效果还是很理想的。

多种类型的文件

我们选取了txtpngwavyuv等10种格式的文件进行LZW编解码实验,并得到了不同文件格式的压缩比:
在这里插入图片描述
压缩比对比如下表所示:

文件类型编码前大小编码后大小压缩比
txt9 bytes16 bytes56.25%
yuv9.37 KB5.65 KB165.84%
pdf197 KB214 KB92.05%
xlsx11.1 KB19.4 KB57.21%
docx1.36 MB1.67 MB81.43%
avi8.30 MB9.99 MB83.08%
wav44.2 KB54.8 KB80.65%
jpg157 KB212 KB74.05%
png157 KB214 KB73.36%
pptx1.37 MB1.70 MB80.58%

实验结论

从上表可以看出,LZW在某些文件格式上表现出了很好的压缩效果,而在大部分现有的文件格式中压缩效果并不理想,原因可能有两点:

  1. 绝大部分通用的文件格式本身都是经过压缩的,再使用LZW算法进行压缩可能适得其反,但是像yuv这类未经压缩的数据格式,使用LZW算法后的压缩效果就很可观。
  2. 文件的编码格式要求限制,一部分文件中字符的重复概率很高,而另一部分文件中字符的重复概率很低,造成了LZW在压缩不同文件时展现出相反的效果。

总结来说,LZW算法还存在很大的优化空间,比如我们可以加入霍夫曼编码对索引二次编码等。相比之下,LZW算法更适用于大文件(重复的可能性较大),和内容重复率较高的文件。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CUCKyrie

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值