信息论 哈夫曼编码 与 菲诺编码的实现(对一幅BMP格式的灰度图像(个人 证件照片)进行二元霍夫曼编码和译码。并进行编码效率的计算,对一幅BMP格式的灰度图像进行二 元Fano编码、译码 )

原始图片

灰度处理

编码生成的码表:noldList:

解码后图片

编码结果

fano编码实现

源码:

哈夫曼编码实现

#Writen by james ruslinimport json
from math import log
from tkinter import *
from PIL import Image
pixelFrequen = {} #全局 字典
nodeList = []
codeList = {}
E1 = NONE
E2 = NONEclass node:def __init__(self, leftChild=None, rightChild=None, father=None, value=0, count=None):self.leftChild = leftChildself.rightChild = rightChildself.father = fatherself.value = valueself.count = countdef calculater(p):return -log(p, 2)*pdef efficient(image):row = image.size[0]col = image.size[1]allnumber = row*colh = 0for key in pixelFrequen.keys():h += calculater(pixelFrequen[key] / allnumber)L = 0for key in pixelFrequen.keys():L += len(codeList[str(key)]) * pixelFrequen[key] / allnumberR = h/Lreturn Rdef toGray(string):im = Image.open(string)im = im.convert('L')im.save('C:/Users/user/Desktop/newGray.bmp')return im       #返回图片‘对象’def counter(list):global pixelFrequenfor i in list:if i in pixelFrequen.keys():pixelFrequen[i] += 1else:pixelFrequen[i] = 1def leafNodes(pixelValue): #通过组合数组,构造叶子for i in range(len(pixelValue)):nodeList.append(node(value=pixelValue[i][1], count=str(pixelValue[i][0])))return nodeListdef sortNodes(nodeList):nodeList = sorted(nodeList, key=lambda node: node.value) #按照node.value对node排序return nodeListdef huffmanTree(nodeList):nodeList = sortNodes(nodeList)while len(nodeList) != 1:left = nodeList[0]right = nodeList[1]new = node()new.leftChild = leftnew.rightChild = rightleft.father = newright.father = newnew.value = left.value + right.valuenodeList.remove(left)nodeList.remove(right)nodeList.append(new)nodeList = sortNodes(nodeList)return nodeListdef huffmanCoder(image):width = image.size[0]height = image.size[1]imMatrix = image.load()list = []for i in range(width):for j in range(height):list.append(imMatrix[i, j])counter(list)global pixelFrequenpixel = pixelFrequenpixel = sorted(pixel.items(), key=lambda item: item[1])  #以列表返回可遍历的(键, 值) 元组数组。leafList = leafNodes(pixel)head = huffmanTree(leafList)[0]  #leafList里的结点相互连接,形成树global codeListfor i in leafList:codingNode = icodeList.setdefault(i.count, "")while codingNode != head:if codingNode == codingNode.father.leftChild:codeList[i.count] = '0' + codeList[i.count]else:codeList[i.count] = '1' + codeList[i.count]codingNode = codingNode.fatherresult = ''for i in range(width):for j in range(height):for key, value in codeList.items():if str(imMatrix[i, j]) == key:result = result + valuefile = open('C:/Users/user/Desktop/result.txt', 'w')file.write(result)file1 = open('C:/Users/user/Desktop/codeList.json', 'w')jsObj = json.dumps(codeList)file1.write(jsObj)print("编码结果已写入文件")def decode(width, height):file = open('C:/Users/user/Desktop/result.txt', 'r')codeGet = file.readlines()[0].strip('\n')len = codeGet.__len__()pixelReturn = []global codeListi = 0current = ""current += codeGet[0]flag = 0while i < len:for key in codeList.keys():if current == codeList[key]:pixelReturn.append(key)flag = 1breakif flag == 1:if i == len - 1:breakelse:i = i + 1current = codeGet[i]flag = 0else:i += 1if i < len:current += codeGet[i]else:breakc = Image.new('L', (width, height))t = 0for i in range(width):for j in range(height):c.putpixel((i, j), (int(pixelReturn[t])))t = t + 1c.save('C:/Users/user/Desktop/ReturnedHuffman.bmp')def core():global E1global E2root = Tk(className='刘畅2017212184')root.geometry("600x600+100+0")  # 800宽度,800高度,x,y坐标,左上角label = Label(root)label['text'] = '二元huffman编码'label.pack()L1 = Label(root, text="图像文件的位置:")L1.place(x=130, y=100, width=100, height=50)E1 = Entry(root, bd=5)E1.place(x=270, y=100, width=300, height=40)L2 = Label(root, text="编码效率为:")L2.place(x=130, y=200, width=100, height=50)E2 = Text(root)E2.place(x=270, y=200, width=150, height=40)button = Button(root, text='开始编码', command=main)# 收到消息执行go函数button.place(x=250, y=400, width=70, height=50)root.mainloop()def main():global E1global E2string = E1.get()print(string)image = toGray(string)huffmanCoder(image)row = image.size[0]col = image.size[1]decode(image.size[0], image.size[1])e = efficient(image)E2.insert(INSERT, str(e))
core()

fano编码实现

# Writen by Liu
import copy
from math import log
from tkinter import *
from PIL import Image
import jsonpixelFrequent = {}#键为像素值,键值为数量
nodeList = []   #存放结点
codeList = {}   #键为像素值,键值为码字
E1 = NONE
E2 = NONEclass Node:def __init__(self, leftChild = None, rightChild = None, father = None, value = 0, count = None):self.leftChild = leftChildself.rightChild = rightChildself.father = fatherself.value = valueself.count = countdef calculater(p):return -log(p, 2)*pdef efficient(image):row = image.size[0]col = image.size[1]allnumber = row * colh = 0for key in pixelFrequent.keys():h += calculater(pixelFrequent[key]/allnumber)L = 0for key in pixelFrequent.keys():L += len(codeList[key])*pixelFrequent[key]/allnumberR = h/Lreturn Rdef toGray(string):im = Image.open(string)im = im.convert('L')im.save('C:/Users/user/Desktop/newGray.bmp')return im       # 返回图片‘对象’def counter(list):  # 对像素字典初始化,键为像素,键值为其对应的数量global pixelFrequentfor i in list:if i in pixelFrequent.keys():pixelFrequent[i] += 1else:pixelFrequent[i] = 1def leafNode(pixelValueList):for i in range(len(pixelValueList)):nodeList.append(Node(value = pixelValueList[i][1], count = pixelValueList[i][0]))return nodeListdef sortNode(codeList):codeList = sorted(codeList, key=lambda Node: Node.value)return codeListdef initcodeList(list):  # list = pixelFrequent(keys())  #初始化编码表,键值为空串global codeListlength = len(list)for i in range(length):codeList.setdefault(list[i], "")def sortList(list):  # 通过字典的键值进行字典的访问排序global pixelFrequentTemplist = sorted(pixelFrequent.items(), key=lambda item: item[1])length = len(Templist)for i in range(length):list.append(Templist[i][0])return listdef FanoProgress(paralist):  # list = pixelFrequent(keys()),对list排序 ,对编码表进行更新,递归list = copy.copy(paralist)global pixelFrequentglobal codeListvalue_all = 0length = len(list)if length == 1:return 0for i in range(length):value_all += pixelFrequent[list[i]]count1 = 0count2 = 0for i in range(int((length*2)/3)):count1 += pixelFrequent[list[i]]distance = 0distance2 = 0if value_all - 2 * count1 > 0:while True:count1 = count1 + pixelFrequent[list[int((length*2)/3)+distance]]distance += 1if value_all - 2 * count1 <= 0:count2 = count1 - pixelFrequent[list[int((length*2)/3)+distance - 1]]breakif abs(value_all - 2 * count1) > abs(value_all - 2 * count2):distance -= 1else:distance -= 0listlower = copy.copy(list)listHigher = copy.copy(list)for i in range(int((length*2)/3) + distance):codeList[list[i]] = codeList[list[i]] + '1'listHigher.remove(list[i])for j in range(int((length*2)/3) + distance, length):codeList[list[j]] = codeList[list[j]] + '0'listlower.remove(list[j])FanoProgress(listlower)FanoProgress(listHigher)elif value_all - 2 * count1 < 0:while True:count1 = count1 - pixelFrequent[list[int((length*2)/3) - distance2-1]]distance2 += 1if value_all - 2 * count1 >= 0:count2 = count1 + pixelFrequent[list[int((length*2)/3) - distance2]]breakif abs(value_all - 2 * count1) > abs(value_all - 2 * count2):distance2 -= 1else:distance2 -= 0listlower = copy.copy(list)listHigher = copy.copy(list)for i in range(int((length*2)/3) - distance2):codeList[list[i]] += '1'listHigher.remove(list[i])for j in range(int((length*2)/3) - distance2, length):codeList[list[j]] += '0'listlower.remove(list[j])FanoProgress(listlower)FanoProgress(listHigher)else:listlower = copy.copy(list)listHigher = copy.copy(list)for i in range(int((length*2)/3)):codeList[list[i]] += '1'listHigher.remove(list[i])for j in range(int((length*2)/3), length):codeList[list[j]] += '0'listlower.remove(list[j])FanoProgress(listlower)FanoProgress(listHigher)def Fanocoder(im):  # 读取像素列表,对应编码表进行编码imMatrix = im.load()width = im.size[0]height = im.size[1]pixelList = []for i in range(width):for j in range(height):pixelList.append(imMatrix[i, j])counter(pixelList)list = []list = sortList(list)initcodeList(list)FanoProgress(list)result = ""  # 编码结果,对每个像素点进行Fano编码for i in range(width):for j in range(height):for key, values in codeList.items():if imMatrix[i, j] == key:result = result + valuesfile = open('C:/Users/user/Desktop/FanoResult.txt', 'w')file.write(result)file1 = open('C:/Users/user/Desktop/FanoCodeList.json', 'w')jsObj = json.dumps(codeList)file1.write(jsObj)print("编码结果已写入文件")def decode(width, height):file = open('C:/Users/user/Desktop/FanoResult.txt', 'r')codeGet = file.readlines()[0].strip('\n')len = codeGet.__len__()pixelReturn = []global codeListi = 0current = ""current += codeGet[0]flag = 0while i < len:for key in codeList.keys():if current == codeList[key]:pixelReturn.append(key)flag = 1breakif flag == 1:if i == len - 1:breakelse:i = i + 1current = codeGet[i]flag = 0else:i += 1if i < len:current += codeGet[i]else:breakc = Image.new('L', (width, height))t = 0for i in range(width):for j in range(height):c.putpixel((i, j), pixelReturn[t])t = t + 1c.save('C:/Users/user/Desktop/Returnedfano.bmp')def core():global E1global E2root = Tk(className='刘畅2017212184')root.geometry("600x600+100+0")  # 800宽度,800高度,x,y坐标,左上角label = Label(root)label['text'] = '二元Fano编码'label.pack()L1 = Label(root, text="图像文件的位置:")L1.place(x=130, y=100, width=100, height=50)E1 = Entry(root, bd=5)E1.place(x=270, y=100, width=300, height=40)L2 = Label(root, text="编码效率为:")L2.place(x=130, y=200, width=100, height=50)E2 = Text(root)E2.place(x=270, y=200, width=150, height=40)button = Button(root, text='开始编码', command=main)# 收到消息执行go函数button.place(x=250, y=400, width=70, height=50)root.mainloop()def main():global E1global E2string = E1.get()image = toGray(string)Fanocoder(image)decode(image.size[0], image.size[1])R = efficient(image)E2.insert(INSERT, str(R))
core()

如果需要实验报告,进行详细的算法解释,以及获取完整的工程,到这里下载

信息论 哈夫曼编码 与 菲诺编码的实现(对一幅BMP格式的灰度图像(个人 证件照片)进行二元霍夫曼编码和译码。并进行编码效率的计算,对一幅BMP格式的灰度图像进行二 元Fano编码、译码 )相关推荐

  1. 灵光一现的创造——霍夫曼编码

    点击上方"LiveVideoStack"关注我们 作者 | Alex 技术审校 | 赵军 霍夫曼 声影传奇 #004# 作为一名科学家和老师,我真的非常执着.如果我觉得自己还没有找 ...

  2. labview霍夫曼编码_为什么霍夫曼编码好?

    7 个答案: 答案 0 :(得分:3) 如果为最常用使用的符号指定较少的数字或位或较短的代码字词,则可以节省大量存储空间. 假设您要为英文字母分配26个唯一代码,并希望根据这些代码存储英文小说(仅限字 ...

  3. 【数据结构】图解霍夫曼编码,看了就能懂

    今天来给大家普及一下霍夫曼编码(Huffman Coding),一种用于无损数据压缩的熵编码算法,由美国计算机科学家大卫·霍夫曼在 1952 年提出--这么专业的解释,不用问,来自维基百科了. 说实话 ...

  4. 算法科普:有趣的霍夫曼编码

    前言 霍夫曼编码 ( Huffman coding ) 是一种可变长的前缀码.霍夫曼编码使用的算法是 David A. Huffman 还是在MIT 的学生时提出的,并且在 1952 年发表了名为&l ...

  5. Zlib压缩算法:LZ77、LZ78、霍夫曼编码、滑动窗口、Rabin-Karp算法、哈希链、I/O缓冲区

    Table of Contents 1.简介 1.1 什么是zlib 2.压缩算法 2.1 放气 2.2 LZ77 2.2.1 滑动窗口 2.2.2 长距离对 2.3 霍夫曼编码 3. zlib的实现 ...

  6. 数据结构与算法之霍夫曼编码解码实现

    目标:将字符串"can you can a can as a can canner can a can."编码再解码 流程: 将字符串转成bytes (byte[]格式)(eg.[ ...

  7. 学弟学妹们,学会霍夫曼编码后,再也不用担心网络带宽了!

    CSDN 的学弟学妹们,大家好,我是沉默王二. 今天来给大家普及一下霍夫曼编码(Huffman Coding),一种用于无损数据压缩的熵编码算法,由美国计算机科学家大卫·霍夫曼在 1952 年提出-- ...

  8. [多媒体]霍夫曼编码详解

    霍夫曼编码(Huffman Coding)_summer-CSDN博客_霍夫曼编码霍夫曼编码(Huffman Coding)是一种编码方法,霍夫曼编码是可变字长编码(VLC)的一种.霍夫曼编码使用变长 ...

  9. 霍夫曼编码(Huffman Coding)

    霍夫曼编码(Huffman Coding)是一种编码方法,霍夫曼编码是可变字长编码(VLC)的一种. 霍夫曼编码使用变长编码表对源符号(如文件中的一个字母)进行编码,其中变长编码表是通过一种评估来源符 ...

最新文章

  1. vue拖动改变模板_可视化拖拽 UI 布局之拖拽篇
  2. 【网络安全】域渗透之完全绕开安全组件
  3. hyperstudy联合matlab,HyperStudy对后处理排气管道参数的灵敏度分析及优化设计
  4. ES5-6 作用域、作用域链、预编译、闭包基础
  5. 第六章 计算机网络与i教案,大学计算机基础教案第6章计算机网络基础与应用.docx...
  6. Centos 7和 Centos 6开放查看端口 防火墙关闭打开
  7. 2021方便速食行业洞察报告
  8. 手把手教你Windows环境下配置Git环境
  9. 2016-11-15NOIP模拟赛
  10. python3-爬取cnnvd漏洞库
  11. 基于ROS的仿人机器人运动规划与实现
  12. try-catch-finally中的4个大坑,老程序员也搞不定
  13. 微信IOS navigator.getUserMedia undefined
  14. 王者荣耀账号转服务器,王者荣耀账号如何跨系统转移
  15. div+CSS浏览器兼容问题整理(IE6.0、IE7.0 ,ie8 , FireFox...)
  16. 错题本——数据结构(线性表)
  17. wps通过vb宏来查看文档中使用的所有字体
  18. 字体在win10下显示模糊,有锯齿
  19. 机器学习入门-西瓜书总结笔记第十五章
  20. h5 java实现微信分享_WebApp实现微信分享功能

热门文章

  1. 混凝土地坪机器人_地面整平机器人:精准又高效,轻松摆“平”混凝土
  2. 逆向调试雷电思路总结
  3. 实用的java代码生成器,开箱即用(基于mybatisplus的AutoGenerator)
  4. [go]---从java到go(02)---一个简单的handler模式的实现
  5. iOS应用横竖屏切换
  6. 实验四Java_《Java实验四》
  7. idea无法导入主题jar包_总结IDEA开发的26个常用设置
  8. python tcl smb_python操作samba
  9. 为什么c语言读文件少内容,这个程序为什么在读文件时候读不全数据?
  10. hdfs文件如何导出到服务器,[Hadoop] 如何将 HDFS 文件导出到 Windows文件系统