目录
一、 实验项目名称
LZW编解码算法实现与分析
二、 实验目的
掌握词典编码的基本原理,用C/C++/Python等语言编程实现LZW解码器并分析编解码算法。
三、实验内容
1.LZW编码原理
LZW的编码思想是不断地从字符流中提取新的字符串,通俗地理解为新“词条”,然后用“代号”也就是码字表示这个“词条”。这样一来,对字符流的编码就变成了用码字去替换字符流,生成码字流,从而达到压缩数据的目的。LZW编码是围绕称为词典的转换表来完成的。LZW编码器通过管理这个词典完成输入与输出之间的转换。LZW编码器的输入是字符流,字符流可以是用8位ASCII字符组成的字符串,而输出是用n位(例如12位)表示的码字流。LZW编码算法的步骤如下:
步骤1:将词典初始化为包含所有可能的单字符,当前前缀P初始化为空。
步骤2:当前字符C=字符流中的下一个字符。
步骤3:判断P+C是否在词典中。
如果“是”,则用C扩展P,即让P=P+C,返回到步骤2。
如果 “否”,则输出与当前前缀P相对应的码字W;将P+C添加到词典中;令P=C,并返回 到步骤2。
1.LZW解码原理
LZW解码算法开始时,译码词典和编码词典相同,包含所有可能的前缀根。具体解码算法如下:
步骤1:在开始译码时词典包含所有可能的前缀根。
步骤2:令CW:=码字流中的第一个码字。
步骤3:输出当前CW指向的字符串string.CW到码字流。
步骤4:先前码字PW:=当前码字CW。
步骤5:当前码字CW:=码字流的下一个码字。
步骤6:判断当前CW指向的字符串string.CW 是否在词典中。
如果”是”,则把当前CW指向的字符串string.CW输出到字符流。当前前缀P:=先前PW指 向的字符串string.PW。当前字符C:=当前CW指向的字符串string.CW的第一个字符。把 字符串P+C添加到词典。
如果”否”,则当前前缀P:=先前PW指向的字符串string.PW。当前字符C:=当前CW指向 的字符串string.CW的第一个字符。输出字符串P+C到字符流,然后把它添加到词典中。
步骤7:判断码字流中是否还有码字要译。
如果”是”,就返回步骤4。
如果”否”,结束。
四、实验步骤
1.编码程序部分:
void LZWEncode(FILE* fp, BITFILE* bf)
{
int character;
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();
while( EOF!=(character=fgetc( fp)))
{
index = InDictionary( character, string_code);
if( 0<=index)
{// string_code+character在词典中找到了
string_code = index;
}else{
// string_code+character在词典中没找到
output( bf, string_code); //写入bf
if( MAX_CODE > next_code)
{// 有空余空间
// 添加 string+character 进词典
AddToDictionary( character, string_code);
}
string_code = character;
}
}
output( bf, string_code);
}
这里先以一个简单的文本文件作为输入,得到输出的LZW编码文件:
以二进制文件方式打开:
上面为编码后的文件,下面为编码前的文件
0000001E | 30,表示文件大小,这里用了四个字节来表示,写在编码后文件开头 |
0061 0062 0062 | a b b,表示这三个字符的码字,这里用两个字节来表示(后续会有>256的码字因此用了16位) |
0100 0103 | ab aba,256 259,这里是通过词典编码,用这两个码字代替了原来的字符串 |
2. 解码程序部分:
将上面简单文本编码得到的文件再进行解码
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; //上一个码字初始化为-1
while (0 < file_length)
{
new_code = input(bf);
if (new_code >= next_code)
{//当前读到的索引号大于词典中索引号
//即为新词条
d_stack[0] = character; //上一个字符串第一位
phrase_length = DecodeString(1, last_code);//当前码字对应的字符或字符串长度
}
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)
{// 将新词条添加进词典,上一个字符串与当前字符串第一位
AddToDictionary(character, last_code);
}
last_code = new_code;
}
}
解码得到的文件内容与原未编码文件一致:
解码端要重点理解当前码字在词典中不存在的原因以及应如何处理:
解码端解码时出现不在词典里的码字的原因,是因为编码端刚刚将这个字符串的码字写入词典,下一个字符串就立刻用了,编码端和解码端编写新词条的过程相似,但是编码端是对着字符串直接新词条编写,而解码端是解出来之后进行新词条编写,二者有一个时间差。所以当编码端立刻使用新词条时,解码端还没有形成这个新词条。
但是有简单的解决办法,既然已经明白原因是因为立刻使用了新词条,仔细看编码端的编码过程,就知道这个新词条第一位和上一个字符串第一位一致,而且是上一个字符串与这个第一位的组合:
因此碰到新码字,代码段只需要保存上一个字符串第一位,将上一个字符串与这个第一位组成新字符串,输出并写入词典即可。
五、实验结果
选择至少十种不同格式类型的文件,使用LZW编码器进行压缩得到输出的压缩比特流文件。对各种不同格式的文件进行压缩效率的分析。
选择的文件类型如下:
图像 | png jpg bmp |
文本 | txt docx pdf |
音频 | mp3 wav |
视频 | mp4 avi |
压缩 | rar zip |
最终压缩情况如下:
文件冗余度更高,重复内容更多,压缩比就更小;有压缩文件格式冗余度比较低,采用词典编码相比无压缩的格式压缩比应该更高
图像选择了一幅背景白色的纯线条图像,分别保存为png、jpg、bmp,由于图像特殊性png反而比jpg文件要小,压缩比更高,个人认为jpg背景白色冗余较多,因此采用词典编码还能压缩,bmp未压缩文件更不必说,通过编码可以压缩至很小。
文本选择一篇英文文本,分别保存为txt、docx、pdf,对于txt使用词典编码压缩性能比较好,压缩比低,其次是pdf,最后是docx。
音频和视频内容也分别一致,avi和wav比mp4和mp3使用词典编码压缩比更小。
六、附件
头文件LZW.h
#ifndef LZW_H_
#define LZW_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);
void InitDictionary();
int InDictionary(int character, int string_code);
void AddToDictionary(int character, int string_code);
void PrintDictionary();
void LZWEncode(FILE* fp, BITFILE* bf);
void LZWDecode(BITFILE* bf, FILE* fp);
int DecodeString(int start, int code);
#endif
File.cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <math.h>
#include "LZW.h"
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;
}
}
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);
}
LZW.cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <math.h>
#include "LZW.h"
#define MAX_CODE 65535
#define input(f) ((int)BitsInput( f, 16)) //16位码字
#define output(f, x) BitsOutput( f, (unsigned long)(x), 16)
struct {
int suffix; //新字符
int parent; //母结点,旧串
int firstchild; //第一个孩子结点
int nextsibling;//下一个兄弟结点
}dictionary[MAX_CODE+1];
int next_code;
int d_stack[MAX_CODE];
int string_code; //保存上一个字符或字符串
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 PrintDictionary() {
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");
}
}
void InitDictionary()
{
for (int 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;
string_code = -1;
}
int InDictionary(int character, int string_code) {
//查找词典中是否有string_code+character字符串
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) {
//character:传来的字符;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 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();
while( EOF!=(character=fgetc( fp)))
{
index = InDictionary( character, string_code);
if( 0<=index)
{// string_code+character在词典中找到了
string_code = index;
}else{
// string_code+character在词典中没找到
output( bf, string_code); //写入bf
if( MAX_CODE > next_code)
{// 有空余空间
// 添加 string+character 进词典
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; //上一个码字初始化为-1
while (0 < file_length)
{
new_code = input(bf);
if (new_code >= next_code)
{//当前读到的索引号大于词典中索引号
//即为新词条
d_stack[0] = character; //上一个字符串第一位
phrase_length = DecodeString(1, last_code);//当前码字对应的字符或字符串长度
}
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)
{// 将新词条添加进词典,上一个字符串与当前字符串第一位
AddToDictionary(character, last_code);
}
last_code = new_code;
}
}
main.cpp
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <math.h>
#include "LZW.h"
int main(int argc,char*argv[])
{
FILE* en = NULL; //指向编码前文件指针
BITFILE* result = NULL; //指向编码后解码前文件指针
FILE* de = NULL; //指向解码后文件指针
if ('E' == argv[1][0]) //编码
{
printf("进行编码\n");
en = fopen(argv[2], "rb");
result = OpenBitFileOutput(argv[3]);
if (en == NULL)
{
printf("找不到输入文件\n");
exit(1);
}
if (result == NULL)
{
printf("找不到输出文件\n");
exit(1);
}
LZWEncode(en, result);
fclose(en);
CloseBitFileOutput(result);
printf("编码完成\n");
}
if ('D' == argv[1][0]) //解码
{
printf("进行解码\n");
result = OpenBitFileInput(argv[2]);
de = fopen(argv[3], "wb");
if (result == NULL)
{
printf("找不到输入文件\n");
exit(1);
}
if (de == NULL)
{
printf("找不到输出文件\n");
exit(1);
}
LZWDecode(result, de);
CloseBitFileInput(result);
fclose(de);
printf("解码完成\n");
}
//PrintDictionary();
return 0;
}