-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHuffmanAlgorithm.py
More file actions
205 lines (161 loc) · 7.31 KB
/
HuffmanAlgorithm.py
File metadata and controls
205 lines (161 loc) · 7.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# Seyyedali Shohadaalhosseini - alishhde
import math
from itertools import chain
from numpy import array
import matplotlib.pyplot
import matplotlib.image as mpimg
def main():
print("Reading your Input image...")
pixels_flattened, img_pixels_matrix = Read_input()
print("Calculating Symbols and their frequencies...")
symbols, frequencies = calculateThePixelsAndFrequency(pixels_flattened, img_pixels_matrix)
symbolAndFrequency = connectSymbolsToFrequencies(symbols, frequencies)
print("Encoding data...")
codesOfData = huffmanEncoding(symbolAndFrequency)
print("Data encoded.")
codedDataSent = huffmanSendCodedData(img_pixels_matrix, codesOfData)
print("Decoding data...")
huffmanDecoding(codedDataSent, codesOfData)
print("Data decoded.")
entropy = sourceEntropy(frequencies)
print("The Entropy is :", entropy)
minimumAverage = minimumAverageNumberOfBit(codesOfData, symbolAndFrequency)
print("This is Minimum Average Number Of Bit: ", minimumAverage)
def Read_input(imagePath='D:\Teachers\DR M. Rostaee\Multimedia\Exercises\HW1\img0-gray.jpg'):
img_pixels_matrix = mpimg.imread(imagePath)
img_pixels_flattened = list(chain(*img_pixels_matrix)) # here we have flattened our list
return img_pixels_flattened, img_pixels_matrix
def huffmanEncoding(symbolAndFrequency):
symbolsCode = list()
TreeNodes = list()
rootNodes = list()
c = 0
while len(symbolAndFrequency) > 1:
SortedSymbolFreq = sortTheDataBy(symbolAndFrequency)
low, lower, symbolAndFrequency = returnTwoLowest(SortedSymbolFreq)
lowestSum = low[1] + lower[1]
if len(TreeNodes) > 0:
rootNodes = [val[0] for val in TreeNodes]
if str(low[0]) in rootNodes and str(lower[0]) in rootNodes:
# deleting the repeated node to replace with new one
index_Counter = 0
for val in TreeNodes:
if val[0] == str(low[0]):
del TreeNodes[index_Counter]
elif val[0] == str(lower[0]):
del TreeNodes[index_Counter]
index_Counter += 1
TreeNodes.append(["{}-{}".format(low[0], lower[0]), lowestSum]) # Append the new one
symbolAndFrequency.append(["{}-{}".format(low[0], lower[0]), lowestSum])
listToCheck = low[0].split("-")
symbolsIn_symbolsCode = [s[0] for s in symbolsCode]
for symb in listToCheck:
symbIndex = symbolsIn_symbolsCode.index(symb)
symbolsCode[symbIndex][1] = "0{}".format(symbolsCode[symbIndex][1])
listToCheck = lower[0].split("-")
symbolsIn_symbolsCode = [s[0] for s in symbolsCode]
for symb in listToCheck:
symbIndex = symbolsIn_symbolsCode.index(symb)
symbolsCode[symbIndex][1] = "1{}".format(symbolsCode[symbIndex][1])
elif str(low[0]) in rootNodes:
# deleting the repeated node to replace with new one
index_Counter = 0
for val in TreeNodes:
if val[0] == str(low[0]):
del TreeNodes[index_Counter]
index_Counter += 1
TreeNodes.append(["{}-{}".format(low[0], lower[0]), lowestSum]) # Append the new one
symbolAndFrequency.append(["{}-{}".format(low[0], lower[0]), lowestSum])
listToCheck = low[0].split("-")
symbolsIn_symbolsCode = [s[0] for s in symbolsCode]
for symb in listToCheck:
symbIndex = symbolsIn_symbolsCode.index(symb)
symbolsCode[symbIndex][1] = "0{}".format(symbolsCode[symbIndex][1])
symbolsCode.append(["{}".format(lower[0]), "1"])
elif str(lower[0]) in rootNodes:
# deleting the repeated node to replace with new one
index_Counter = 0
for val in TreeNodes:
if val[0] == str(lower[0]):
del TreeNodes[index_Counter]
index_Counter += 1
TreeNodes.append(["{}-{}".format(low[0], lower[0]), lowestSum]) # Append the new one
symbolAndFrequency.append(["{}-{}".format(low[0], lower[0]), lowestSum])
listToCheck = lower[0].split("-")
symbolsIn_symbolsCode = [s[0] for s in symbolsCode]
for symb in listToCheck:
symbIndex = symbolsIn_symbolsCode.index(symb)
symbolsCode[symbIndex][1] = "1{}".format(symbolsCode[symbIndex][1])
symbolsCode.append(["{}".format(low[0]), "0"])
else:
symbolsCode.append(["{}".format(low[0]), "0"])
symbolsCode.append(["{}".format(lower[0]), "1"])
TreeNodes.append(["{}-{}".format(low[0], lower[0]), lowestSum])
symbolAndFrequency.append(["{}-{}".format(low[0], lower[0]), lowestSum])
c += 1
return symbolsCode
def calculateThePixelsAndFrequency(img_pixels_flattened, img_pixels_matrix):
symbols = list()
frequencies = list()
max_pixels = img_pixels_matrix.shape[0] * img_pixels_matrix.shape[1] # To calculate the probability
for pixel in img_pixels_flattened:
if pixel in symbols:
continue
symbols.append(pixel)
frequencies.append((img_pixels_flattened.count(pixel)) / max_pixels)
return symbols, frequencies
def connectSymbolsToFrequencies(symbols, frequencies):
connectList = list()
if len(symbols) == len(frequencies):
for index in range(len(symbols)):
connectList.append([symbols[index], frequencies[index]])
return connectList
def sortTheDataBy(data):
data.sort(key=lambda x: x[1], reverse=True)
return data
def returnTwoLowest(SymbolFreq):
low, lower = SymbolFreq[-2], SymbolFreq[-1]
symbolAndFrequency = SymbolFreq[:-2]
return low, lower, symbolAndFrequency
def huffmanSendCodedData(imageMatrix, codesOfData):
dataSent = list() # This list shapes must be (300, 302) as our main image is
CodesIndexes = [ind[0] for ind in codesOfData]
for eachline in imageMatrix:
tempList = list()
for eachValue in eachline:
index = CodesIndexes.index(str(eachValue))
tempList.append(codesOfData[index][1])
dataSent.append(tempList)
return dataSent
def huffmanDecoding(codedDataReceived, codesOfData):
dataReceived = list()
ValuesIndexes = [ind[1] for ind in codesOfData]
for eachLine in codedDataReceived:
tempList = list()
for eachValue in eachLine:
index = ValuesIndexes.index(str(eachValue))
tempList.append(int(codesOfData[index][0]))
dataReceived.append(tempList)
return showTheDecodedData(dataReceived)
def showTheDecodedData(dataToShow):
# First we convert it to the array
dataArray = array(dataToShow)
matplotlib.pyplot.imshow(dataArray, cmap='gray')
matplotlib.pyplot.imsave("Huffman Image.jpg", dataArray, cmap='gray')
matplotlib.pyplot.show()
def sourceEntropy(frequencies):
entropy = 0
for f in frequencies:
entropy += f * math.log2(f)
return entropy * (-1)
def minimumAverageNumberOfBit(codes, probability):
minimumBit = 0
for f in probability:
for t in codes:
if t[0] == str(f[0]):
nBit = len(t[1])
break
minimumBit += nBit * f[1]
return minimumBit
if __name__ == '__main__':
main()