Skip to content

Instantly share code, notes, and snippets.

@night-crawlr
Created December 14, 2021 13:00
Show Gist options
  • Save night-crawlr/c0092db94e5e6954426d4aab5f1353c5 to your computer and use it in GitHub Desktop.
Save night-crawlr/c0092db94e5e6954426d4aab5f1353c5 to your computer and use it in GitHub Desktop.
def sendBinaryData(self, path):
# Our self.encodedString is just list of strigs with characters char('0') & char('1')
# but we should not directly write char('0') and char('1') , because each of them take 1byte = 8bits, so we are converting the char('0') and char('1') to binary(0) & binary(1)
# To do the above work we are using bitstring from BitArray library
from bitstring import BitArray
file = open(path, 'wb')
obj = BitArray(bin=self.encodedString)
obj.tofile(file)
file.close()
def decode(self, path):
# Now we have a file , we will try to read its contents
# For reading binary from file we are using bitarray library (this is different one from above used BitArray)
import bitarray
self.binaryFromFile = bitarray.bitarray()
with open(path, 'rb') as f:
self.binaryFromFile.fromfile(f)
# Data type of self.binaryFromFile is list of int(0)'s and int(1)'s
decodeList = []
root = self.root
temp_root = cp(self.root)
temp_r = 0
temp_c = 0
temp_d = 0
# Like we encoded r,c,d, we will first retrieve/decode them
for i, c_int in enumerate(self.binaryFromFile):
if(temp_r != 0 and temp_c != 0 and temp_d != 0 and len(decodeList) == (temp_r*temp_c*temp_d + 3)):
break
if(temp_r == 0 and len(decodeList) >= 1):
temp_r = decodeList[0]
if(temp_c == 0 and len(decodeList) >= 2):
temp_c = decodeList[1]
if(temp_d == 0 and len(decodeList) >= 3):
temp_d = decodeList[2]
# Start at root, if 0 go to left node, if 1 go to right node, if leafnode is found store the intensity in a list
# and follow the same procedure untill you find (r*c*d + 3) values, ie 3 dimensions and r*c*d intensities
temp_root = temp_root.c[c_int]
if(temp_root.isLeaf):
decodeList.append(temp_root.freq)
temp_root = root
continue
self.decodeList = decodeList
def decodeIm(self, path):
self.decode(path)
# Extracting dimensions values from deocded list, ie its first 3 three
decodeList = self.decodeList
out_r = decodeList[0]
decodeList.pop(0)
out_c = decodeList[0]
decodeList.pop(0)
out_d = decodeList[0]
decodeList.pop(0)
out = np.zeros((out_r, out_c, out_d))
# Filling the out put image
for i in range(len(decodeList)):
id = i//out_d
x = id//out_c
y = id % out_c # Basic parsing mathematics for finding index values
z = i % out_d
out[x][y][z] = decodeList[i]
out = out.astype(dtype=int)
self.out = out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment