实验三----LZW 编解码算法实现与分析

本文档详细介绍了LZW编码和解码原理,并提供了C/C++/Python编程实现LZW编解码的实验目的和步骤。在实验过程中,通过分析不同文件格式的压缩效果,发现LZW编码对某些原始文件格式如.yuv有显著的压缩效果,而对已压缩文件可能增加冗余。
摘要由CSDN通过智能技术生成

1 实验目的

掌握词典编码的基本原理,用C/C++/Python等语言编程实现LZW解码器并分析编解码算法。

2 实验原理

在这里插入图片描述

2.1 LZW编码原理
在这里插入图片描述
1、初始字典包含所有的单字符,初始化P=NULL;
2、将数据流的下一个字符赋给C;
3、判断P+C(P连接C)这个字符是否在字典里:
(1)是——P=P+C;
(2)否——输出P对应的码字CW,将P+C作为新串写入字典,P=C;
4、返回步骤2。

2.2 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)否——结束。

3实验代码

1.头文件

/*
 * 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__

2.文件读取和写入

/*
 * 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

3.LZW编解码

/*
 * 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;//计数器从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; //第255个ASCII字符是最后一个字符,没有兄弟节点
	next_code = 256; //下一个开始编号的号码是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 ++;
}

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();//设置字典的0-255的基本内容
	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; //将返回的index给string_code
		}
		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; //将目前字符的代号放入前缀串
		}
		//PrintDictionary();
	}
	output( bf, string_code);// 将字符串对应的代号写入到二进制文件中
}
/*进行LZW编码的完整流程
* @parameters:二进制文件指针bf,文件指针fp
* @return:None
*/

void LZWDecode( BITFILE *bf, FILE *fp){
	int character; //字符代号
	int new_code, last_code=-1;
	int phrase_length; //
	unsigned long file_length; //文件的长度

	file_length = BitsInput( bf, 4*8);//BitsInput是根据bf和代号的长度,计算出有多少个字符,返回个数给filelength
	if( -1 == file_length) file_length = 0; 

	/*需填充*/
	InitDictionary();//初始化字典
	last_code = -1;//pw=-1;
	while( 0<file_length)
	{
		new_code = input( bf);//读入一个代号,new_code指cw
		if( new_code >= next_code)//如果读入的代号比字典最大代号还大,即该代号不在字典里
		{ // this is the case CSCSC( not in dict)
			d_stack[0] = character;//pw的代号character存入输出字符串最后一个字符中(因为d_stack倒序输出)
			phrase_length = DecodeString( 1, last_code);//解出字符,将pw写入d_stack(因为位置0已经写入pw代号,所以从位置1写入)
		}
		else//如果代号存在于字典中
		{
			phrase_length = DecodeString( 0, new_code);//解出字符,将pw写入d_stack
		}
		character = d_stack[phrase_length-1];//将cw首字符存入character
		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);//将P+C写入字典
		}
		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;
}


1.首先调试LZW的编码程序,以一个文本文件作为输入,得到输出的LZW编码文件。
在这里插入图片描述
在这里插入图片描述

2.以实验步骤一得到的编码文件作为输入,编写LZW的解码程序。在写解码程序时需要对关键语句加上注释(见3 实验代码)在这里插入图片描述
(2)当前码字在字典中不存在的问题
原因:编码时,上一个新的词条刚被创建,下一个词组就需要使用它。即解码端的解码会比编码端晚一步。我们还没有得到最新的词条就需要使用它。
解决方法:下一个词条的尾缀是当前词条的第一个字符,所以就先输出这个字符,然后用前一词条的代号进行解码。

3.选择至少十种不同格式类型的文件,使用LZW编码器进行压缩得到输出的压缩比特流文件。对各种不同格式的文件进行压缩效率的分析。
在这里插入图片描述
对于部分已被压缩过的文件类型,经过LZW编码后,文件变大了,LZW编码反而增加了冗余。而对于.yuv等比较原始,没有经过处理的文件格式来说,经过LZW编码后文件大小显著减小。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值