-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrunlength.py
executable file
·78 lines (57 loc) · 1.94 KB
/
runlength.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 6 15:11:04 2021
@author: root
"""
import numpy as np
from usefuls import ints2bs,bs2ints,write_bits,read_bits,bin2dec2,dec2bin2
import os
def RLED(bits,maxrunl,maxnruns,ENC,fpath):
nbits_needed = int(np.ceil(np.log(maxrunl+1)/np.log(2)))
nnrun_bits = int(np.ceil(np.log(maxnruns+1)/np.log(2)))
if ENC:
start_bit = bits[0]
else:
bs = read_bits(fpath)
start_bit = bs[0]
nruns = bin2dec2(bs[1:(nnrun_bits+1)])
nintbits = nbits_needed*np.ones((nruns,),int)
runls = bs2ints(bs[(nnrun_bits+1):],nintbits)
print('dec runs:')
print(runls)
bits = ''
curr_bit=start_bit
for irun,runl in enumerate(runls):
bits = bits + runl*curr_bit
curr_bit=str(1-int(curr_bit))
return bits
last_bit = start_bit
curr_run_start = 0
if ENC:
runls = np.zeros((len(bits)+1,),int)
irun=0
for ibit,bit in enumerate(bits[1:]):
if bit!=last_bit:
runls[irun] = ibit+1-curr_run_start
curr_run_start = ibit+1
irun +=1
last_bit=bit
runls[irun] = ibit+2-curr_run_start
runls = runls[0:(irun+1)]
print('enc runs:')
print(runls)
nruns = irun+1
bs1 = dec2bin2(nruns,nnrun_bits)
nintbits = nbits_needed*np.ones((nruns,),int)
bs = start_bit + bs1 + ints2bs(runls,nintbits)
write_bits(bs,fpath)
if __name__=="__main__":
bits = '011111000000000'
fpath = 'bs.bs'
print('encoded bits: ' + bits)
RLED(bits, len(bits), len(bits), 1, fpath)
dbits = RLED('', len(bits), len(bits), 0, fpath)
print('decoded bits: ' + dbits)
CL = os.path.getsize(fpath)
print('bitrate:'+str(CL/len(bits)))