数据压缩实验三:LZW编解码算法实现

一、LZW编码原理概述

1.1 LZW的编码思想

不断地从字符流中提取新的字符串,通俗地理解为新“词条”,然后用“代号”也就是码字表示这个“词条”。这样一来,对字符流的编码就变成了用码字去替换字符流,生成码字流,从而达到压缩数据的目的。LZW编码是围绕称为词典的转换表来完成的。LZW编码器通过管理这个词典完成输入与输出之间的转换。LZW编码器的输入是字符流,字符流可以是用8位ASCII字符组成的字符串,而输出是用n位(例如12位)表示的码字流。

1.2 LZW编码算法的步骤

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

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

步骤3:判断P+C是否在词典中(1)如果“是”,则用C扩展P,即让P=P+C,返回到步骤2。(2)如果“否”,则输出与当前前缀P相对应的码字W;将P+C添加到词典中;令P=C,并返回到步骤2LZW编码算法可用下述函数实现。首先初始化词典,然后顺序从待压缩文件中读入字符并按照上述算法执行编码。最后将编得的码字流输出至文件中。

1.3 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)如果”否”,结束。

二、实验步骤

1.首先调试LZW的编码程序,以一个文本文件作为输入,得到输出的LZW编码文件。

2. 以实验步骤一得到的编码文件作为输入,编写LZW的解码程序。在写解码程序时需要对关键语句加上注释,并说明进行何操作。在实验报告中重点说明当前码字在词典中不存在时应如何处理并解释原因。

3. 选择至少十种不同格式类型的文件,使用LZW编码器进行压缩得到输出的压缩比特流文件。对各种不同格式的文件进行压缩效率的分析。

三、实验结果和相关代码

3.1 补充lzw.cpp中缺失代码

3.1.1 DecodeString

int DecodeString(int start, int code) {
	int count = start;
	while (0 <= code) 
	{
		d_stack[count] = dictionary[code].suffix;  //将新字符传入数组
		code = dictionary[code].parent;  //将旧字符赋给code
		count++;  //数组下标增加1
	}
	return count;
}

3.1.2 LZWDecode

void LZWDecode(BITFILE* bf, FILE* fp)
{
	int character;
	int new_code, last_code;   //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; //pw=-1
	while (0 < file_length) {  //解完最后一个码字后退出循环
		new_code = input(bf);  //读入新码字
		if (new_code >= next_code) //如果新码字不在词典中
		{ 
			d_stack[0] = character;  //写character数组,即为pw
			phrase_length = DecodeString(1, last_code);//解码后返回字符串长度
		}
		else //如果新码字在词典中
		{	  
			phrase_length = DecodeString(0, new_code);//直接对应词典解码
		}
		character = d_stack[phrase_length - 1];//将cw的第一个字符存入character,确定pw的值
		while (0 < phrase_length) 
		{ 
			phrase_length--;
			fputc(d_stack[phrase_length], fp);//输出当前对应的字符串
			file_length--;//待解码文件长度-1
		}
		if (MAX_CODE > next_code) 
		{
			AddToDictionary(character, last_code);//将本次涉及到的码字添加到词典中;
                                                  
		last_code = new_code;//新码字变为上一个码字
	}
}

3.2 调试程序编解码

3.2.1 编码

输入调试参数

源txt文件:

编码后txt文件:

3.2.2 解码

调整参数:

解码结果:

解码后的文件与原始文本文件相同。

3.3 回答问题

Q:解码时当前码字在词典中不存在时应如何处理?

A:出现这种情况说明编码端一出现新码字就应用到了码流中。若下一个字符串为刚刚新写入的字符串,则由于延时问题,解码端未同步更新新字符串的索引号,所以会出现当前码字在词典中不存在的情况。此时的新词条一般第一个字符与最后一个字符相同。

因此,可以在解码端将上个码字的第一个符号复制至最后一个符号的位置,则形成的新码字就是我们要解码的当前码字。

3.4 验证编码效率

选择至少十种不同格式类型的文件,使用LZW编码器进行压缩得到输出的压缩比特流文件。对各种不同格式的文件进行压缩效率的分析。

3.4.1 准备10种不同格式文件

3.4.2 依次使用lzw编码器进行压缩

3.4.3 列表对比

 结论:部分文件LZW编码后反而变大,这是由于这些文件本身就经过一定压缩,所以使用LZW编码反而增加了冗余。而对于bmp这类没有经过处理的文件格式来说,经过LZW编码后文件大小大大地减小了。

3.5 原始代码

bitio.h

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

bitio.c

/*
 * Definitions for bitwise IO
 *
 * vim: ts=4 sw=4 cindent
 */
#define _CRT_SECURE_NO_DEPRECATE
#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

lzwcode.c

/*
 * Definition for LZW coding
 *
 * vim: ts=4 sw=4 cindent nowrap
 */
#define _CRT_SECURE_NO_DEPRECATE
#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 = start;
	while (0 <= code) 
	{
		d_stack[count] = dictionary[code].suffix;  //将新字符传入数组
		code = dictionary[code].parent;  //将旧字符赋给code
		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++;
}

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;   //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; //pw=-1
	while (0 < file_length) {  //解完最后一个码字后退出循环
		new_code = input(bf);  //读入新码字
		if (new_code >= next_code) //如果新码字不在词典中
		{ 
			d_stack[0] = character;  //写character数组,即为pw
			phrase_length = DecodeString(1, last_code);//解码后返回字符串长度
		}
		else //如果新码字在词典中
		{	  
			phrase_length = DecodeString(0, new_code);//直接对应词典解码
		}
		character = d_stack[phrase_length - 1];//将cw的第一个字符存入character,确定pw的值
		while (0 < phrase_length) 
		{ 
			phrase_length--;
			fputc(d_stack[phrase_length], fp);//输出当前对应的字符串
			file_length--;//待解码文件长度-1
		}
		if (MAX_CODE > next_code) 
		{
			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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LZW(Lempel-Ziv-Welch)压缩算法是一种无损压缩算法,能够对数据流进行有效压缩。在图像压缩方面,LZW算法可以将原始图像数据流进行压缩,并且不会损失原始图像的任何信息。下面是一个基于 MATLAB 的 LZW 图像压缩编码实现: ```matlab function [compressedImage, dict] = lzw_compress(image) % 将图像转换为一维数据流 data = reshape(image, 1, []); % 初始化编码字典 dict = cell(256, 1); for i = 1:256 dict{i} = uint8(i-1); end % 初始化编码参数 code = 257; p = uint8([]); compressedImage = []; % LZW 编码 for i = 1:numel(data) c = data(i); pc = [p c]; if ismember(pc, dict) p = pc; else compressedImage = [compressedImage uint16(find(ismember(dict, p)))]; dict{code} = pc; code = code + 1; p = c; end end % 将编码后的数据流转换为字节流 compressedImage = typecast(compressedImage, 'uint8'); end ``` 这个函数将输入的图像 `image` 转换为一维数据流 `data`,并且初始化编码字典。接下来,我们对数据流进行 LZW 编码,将编码后的数据转换为字节流并返回。此外,函数还返回了编码字典 `dict`,方便解码时使用。 以下是一个基于 MATLAB 的 LZW 图像解压缩编码实现: ```matlab function image = lzw_decompress(compressedImage, dict) % 将字节流转换为编码数据流 compressedImage = typecast(compressedImage, 'uint16'); % 初始化解码参数 code = 257; p = uint8([]); data = []; % LZW 解码 for i = 1:numel(compressedImage) k = compressedImage(i); if k <= 256 c = dict{k}; else c = [p dict{k}(1)]; end data = [data c]; if ~isempty(p) dict{code} = [p c(1)]; code = code + 1; end p = c; end % 将一维数据流转换为图像 image = reshape(data, size(image)); end ``` 这个函数将输入的压缩后的字节流 `compressedImage` 转换为编码数据流,然后初始化解码参数。接下来,我们对编码数据流进行 LZW 解码,将解码后的数据转换为图像并返回。函数中的解码过程与编码过程不同,因为我们需要在解码过程中构建编码字典。因此,我们使用了一个变量 `code` 来追踪下一个字典条目的编码值。 这是一个简单的 LZW 图像压缩编码实现,可以用于对图像进行无损压缩。需要注意的是,该实现仅支持 8 位灰度图像。如果要支持彩色图像,需要对每个颜色通道分别进行压缩编码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值