bmp图像Huffman编解码程序

本文档详细介绍了如何实现BMP图像的Huffman编码和解码程序,包括编码过程和解码过程的步骤,是图像处理和压缩技术的一个实践应用。
摘要由CSDN通过智能技术生成
编码程序
#include <iostream>
#include <string>
#include <algorithm>//排序函数所用

#include "stdio.h"
#include "Hxlbmpfile.h"
using namespace std;


typedef struct Temp_Node
{
	unsigned char pixel;//ASCII字符
	unsigned long  weight;//权重,像素出现的次数
}Temp_Node;

typedef struct Huf_Node
{
	unsigned char pixel;//ASCII码对应0-255
	unsigned long weight;	//该节点的“重量”:像素次数

	char   *code;		//该节点对应的编码
	int lchild,rchild,parent;	//左右孩子  父节点

	Huf_Node() {parent=0;}//设节点的父节点为空
	
}Huf_Node,*Huf_Tree;



int Getweight(HXLBMPFILE *bmpfile,Temp_Node *tempnodes);//由文件获得像素出现的频率
bool encode(char *bmpfname,char *encodefname);		//对于给定的bmp文件进行编码
void InitializeHufNode(Temp_Node *tempnodes,Huf_Node *nodelist,int charkinds);//初始化叶子节点
void select(Huf_Node *huf_tree,int n,int *s);//找出规定范围没有父节点的节点最小值
void CreateHufTree(Huf_Node *nodelist,int charkinds,int nodenum);		//建立赫夫曼二叉树
void CtreateHufcode(Huf_Node *nodelist,int charkinds);//对叶子结点进行编码
void Save_Encodefile(HXLBMPFILE *bmpfile,char *encodefname,int charkinds,Huf_Node *nodelist);//保存编码文件
bool encode(char *bmpfname,char *encodefname);//进行编码

bool cmp2(Temp_Node a,Temp_Node b)		//比较两个list元素的大小
{
	return a.weight>b.weight;
}

int Getweight(HXLBMPFILE *bmpfile,Temp_Node *tempnodes)
{
	int i,j;
	int nodenum=0;

	for(i=0;i<256;i++)
	{
		(tempnodes+i)->weight=0;
		(tempnodes+i)->pixel=(unsigned char)i;
		//cout<<(int)(tempnodes+i)->pixel<<"\t"<<(tempnodes+i)->weight<<endl;
	}

	for(i=0;i<bmpfile->imageh;i++)//获取总像素的
	{
		for(j=0;j<bmpfile->imagew;j++)
		{
			(tempnodes+bmpfile->pDataAt(i)[j])->weight+=1;
	
		}
	}

	sort(tempnodes,tempnodes+256,cmp2);

	for(i=0;i<256;i++)//共有多少个像素出现过
	{
		//cout<<(int)(tempnodes+i)->pixel<<"\t"<<(tempnodes+i)->weight<<endl;
		if((tempnodes+i)->weight>0&&(tempnodes+i+1)->weight==0)
			nodenum=i+1;
	}
	return nodenum;
	
}

void InitializeHufNode(Temp_Node *tempnodes,Huf_Node *nodelist,int charkinds)//初始化叶子节点
{
	int i=0;
	

	for(i=0;i<charkinds;i++)
	{
		(nodelist+i)->weight=(tempnodes+i)->weight;
		(nodelist+i)->pixel=(tempnodes+i)->pixel;
		(nodelist+i)->lchild=-1;
		(nodelist+i)->rchild=NULL;
	}
}


void select(Huf_Node *huf_tree,int n,int *s)//找出规定范围没有父节点的节点最小值
{
	unsigned long m=ULONG_MAX;//无符号长整数最大值

	for(int i=0;i<n;i++)
	{
		if(!huf_tree[i].parent&&huf_tree[i].weight<m)
		{
			m=huf_tree[i].weight;
			*s=i;
		}
	}
	huf_tree[*s].parent=1;
}

void CreateHufTree(Huf_Node *nodelist,int charkinds,int nodenum)		//建立二叉树
{
	int i;
	int s1=0,s2=0;

	for(i=charkinds;i<noden
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值