4 def calcular_entropia(bitstream
):
8 p0
= bitstream
.count('0') / n
9 p1
= bitstream
.count('1') / n
14 entropia
-= p
* math
.log2(p
)
17 def calcular_entropia_condicional(bitstream
):
18 transicoes
= {'00': 0, '01': 0, '10': 0, '11': 0}
19 contagem_base
= {'0': 0, '1': 0}
21 for i
in range(len(bitstream
) - 1):
22 par
= bitstream
[i
:i
+2]
24 contagem_base
[bitstream
[i
]] += 1
27 for base
in ['0', '1']:
28 p_base
= contagem_base
[base
] / (len(bitstream
) - 1)
31 for prox
in ['0', '1']:
32 p_transicao
= transicoes
[base
+ prox
] / contagem_base
[base
]
34 h_local
-= p_transicao
* math
.log2(p_transicao
)
35 h_condicional
+= p_base
* h_local
39 def clean_image_data(image_data
):
43 for line
in image_data
:
45 line
= line
.replace(" ", "")
46 if not line
or line
.startswith('#'):
52 with open(sys
.argv
[1], "r") as image
:
53 lines
= image
.readlines()
54 image_data
= clean_image_data(lines
[2:])
56 h_x
= calcular_entropia(image_data
)
57 h_condicional
= calcular_entropia_condicional(image_data
)
59 print(f
"Entropia: {h_x:.4f} bits/pixel")
60 print(f
"Entropia Condicional: {h_condicional:.4f} bits/pixel")