Skip to content

Instantly share code, notes, and snippets.

@night-crawlr
Created December 14, 2021 12:44
Show Gist options
  • Save night-crawlr/3c2c900731261ce50bd0384859d1863b to your computer and use it in GitHub Desktop.
Save night-crawlr/3c2c900731261ce50bd0384859d1863b to your computer and use it in GitHub Desktop.
# Creating Nodes for intensities
def buildNodes(self):
for key in self.prob_dict:
leaf = Node(key, self.prob_dict[key], 1)
self.allNodes.append(leaf)
# comparator function for sorting
def prob_key(self, e):
return e.prob
# Creating UPTREE
def upTree(self):
import heapq
self.buildNodes() # Creating Nodes
# Sorting all Nodes in workspace to create uptree
workspace = sorted(cp(self.allNodes), key=self.prob_key)
while(1):
c1 = workspace[0]
c2 = workspace[1]
workspace.pop(0)
workspace.pop(0)
# Creating A new node from two smallest propability intensities
new_node = Node(-1, c1.prob+c2.prob)
new_node.c[0] = c1
new_node.c[1] = c2
workspace = list(heapq.merge(
workspace, [new_node], key=self.prob_key)) # Pushing the created Node into Workspace
# Break if probability of prepared node is 1, indicating preparing upTree is completed
if(new_node.prob == 1.0):
self.root = new_node # And storing it as root Node
return
# Creating Down Tree ie assigning words to Leaf Nodes from Root
def downTree(self, root, word):
root.word = word
if(root.isLeaf):
self.leafNodes[root.freq] = root.word
if(root.c[0] != None):
self.downTree(root.c[0], word+'0')
if(root.c[1] != None):
self.downTree(root.c[1], word+'1')
def huffmanAlgo(self):
self.upTree() # Creating UpTree
self.downTree(self.root, "") # Creating DownTree
dicti = {} # Storing the prob_dict in new variable dicti
# So that we need not access ("self.") every time that costs time, we just use dicti in place of self.leafNodes
for key in self.leafNodes:
dicti[key] = self.leafNodes[key]
# Storing the self.encodedString in new variable encodedString
# So that we need not accecess "self." every time,which cost more time
encodedString = ""
encodedString += dicti[self.r]
encodedString += dicti[self.c]
encodedString += dicti[self.d]
# Note we are first encoding dimensions, and later encoding each pxl in 3rd dimension order , later while decoding we decode in the same way
for i in range(self.r):
for j in range(self.c):
for ch in range(self.d):
encodedString += dicti[self.im[i][j][ch]]
self.encodedString = encodedString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment