def uncompress(inputFile, outputFile): # Check that it's a known file if inputFile.readline() != headerText + '\n': sys.stderr.write("Input is not in the '%s' format.\n" % headerText) sys.exit(1) # Read the rows, columns, and channels. rows, columns, channels = [int(x) for x in inputFile.readline().split()] # Read the raw bytes. inputBytes = bytearray(inputFile.read()) # Build the image # # REPLACE THIS WITH YOUR OWN CODE TO CONVERT THE 'inputBytes' ARRAY INTO AN IMAGE IN 'img'. startTime = time.time() img = np.empty([rows, columns, channels], dtype=np.uint8) byteIter = iter(inputBytes) for y in range(rows): for x in range(columns): for c in range(channels): img[y, x, c] = byteIter.next() endTime = time.time() # Output the image netpbm.imsave(outputFile, img) sys.stderr.write('Uncompression time: %.2f seconds\n' % (endTime - startTime))
def uncompress(inputFile, outputFile): # Check that it's a known file if inputFile.readline() != headerText + '\n': sys.stderr.write("Input is not in the '%s' format.\n" % headerText) sys.exit(1) # Read the rows, columns, and channels. rows, columns, channels = [int(x) for x in inputFile.readline().split()] # Read the raw bytes. inputBytes = bytearray(inputFile.read()) # Build the image # REPLACE THIS WITH YOUR OWN CODE TO CONVERT THE 'inputBytes' ARRAY INTO AN IMAGE IN 'img'. startTime = time.time() img = np.empty([rows, columns, channels], dtype=np.uint8) ''' byteIter = iter(inputBytes) for y in range(rows): for x in range(columns): for c in range(channels): img[y,x,c] = byteIter.next() ''' # construct initial dictionary dict_size = 256 dictionary = { i + 256: struct.pack("h", i) for i in xrange(-dict_size, dict_size) } # due to string concatenation in a loop diff = [] byte = iter(inputBytes) # LZW uncompression # read two bytes from the bytearray and take the sum, this gives you the original key a = byte.next() b = byte.next() index = a + b # an integer s = dictionary[index] diff.append(struct.unpack("h", s)[0]) for i in xrange(len(inputBytes) / 2 - 1): a = byte.next() b = byte.next() index = a + b # an integer if index in dictionary: t = dictionary[index] else: stemp = struct.unpack('h', s)[0] t = s + struct.pack("h", stemp) diff.append(struct.unpack("h", t)[0]) if len(dictionary) < 65536: ttemp = struct.unpack('h', t)[0] dictionary[dict_size + 257] = s + struct.pack("h", ttemp) dict_size += 1 s = t diffs = iter(diff) for y in range(rows): for x in range(columns): for c in range(channels): if i < len(diff): prediction = int(img[y - 1, x, c]) + ( int(img[y, x - 1, c]) - int(img[y - 1, x - 1, c])) / 2 img[y, x, c] = diffs.next() + prediction i += 1 sys.stdout.write("Inputbyte length:" + str(len(inputBytes) / 2 - 1)) sys.stdout.write("Diff: " + str(len(diff))) endTime = time.time() # Output the image netpbm.imsave(outputFile, img) sys.stderr.write('Uncompression time: %.2f seconds\n' % (endTime - startTime))
def uncompress(inputFile, outputFile): # Check that it's a known file if inputFile.readline() != headerText + '\n': sys.stderr.write("Input is not in the '%s' format.\n" % headerText) sys.exit(1) # Read the rows, columns, and channels. counter rows, columns, channels = [int(x) for x in inputFile.readline().split()] # Read the raw bytes. inputBytes = bytearray(inputFile.read()) # Build the image # # REPLACE THIS WITH YOUR OWN CODE TO CONVERT THE 'inputBytes' ARRAY INTO AN IMAGE IN 'img'. startTime = time.time() result = [] # initialize the dictionary in the opposite was as compress and use an array as the value d = {} # create a dictionary counter = 256 # Initialize dictionary with values equalling keys from [-256,256] for i in range(-counter, counter): d[i] = [i] img = np.empty([rows, columns, channels], dtype=np.uint8) byteIter = iter(inputBytes) # Get encoding in the form of next two bytes enc = (byteIter.next() << 8) + byteIter.next() s = d[enc] #print s result.append(s[0]) for i in range(1, len(inputBytes) // 2): # again reset the dictionary if it reaches the limit # Initialize dictionary with values equalling keys from [-256,256] if counter >= twoBytes: d = {} # initialize blank dictionary counter = 256 for i in range(-counter, counter): d[i] = [i] enc = (byteIter.next() << 8) + byteIter.next() #retrieve value of dictionary entry from dictionary or create entry assuming it has not yet been entered into dictionary if enc in d: d_value = d[enc] else: d_value = [] for j in s: d_value.append(j) d_value.append(s[0]) #add dictionary entry value to the result for k in range(len(d_value)): result.append(d_value[k]) #Create entry in dictionary temp = [] for j in s: temp.append(j) temp.append(s[0]) d[counter] = temp counter += 1 # reset decoded string to dictionary entry value s = d_value #implement predictive encoding prediction = 0 counter = 0 # for a single channel image if (channels == 1): # Go through whole image for y in range(rows): for x in range(columns): #''' if (x != 0): prediction = img[y][x - 1] elif (y != 0): prediction = img[y - 1][x] else: prediction = (img[y][x - 1] / 3 + img[y - 1][x] / 3 + img[y - 1][x - 1] / 3) #''' img[y, x] = result[counter] + prediction counter += 1 for y in range(rows): for x in range(columns): for c in range(channels): #"""" if (x != 0): prediction = img[y][x - 1][c] elif (y != 0): prediction = img[y - 1][x][c] else: prediction = (img[y][x - 1][c] / 3 + img[y - 1][x][c] / 3 + img[y - 1][x - 1][c] / 3) #"""" img[y, x, c] = result[counter] + prediction counter += 1 endTime = time.time() # Output the image netpbm.imsave(outputFile, img) sys.stderr.write('Uncompression time: %.2f seconds\n' % (endTime - startTime))
def uncompress( inputFile, outputFile ): # Check that it's a known file if inputFile.readline() != headerText + '\n': sys.stderr.write( "Input is not in the '%s' format.\n" % headerText ) sys.exit(1) # Read the rows, columns, and channels. img_dims = [ int(x) for x in inputFile.readline().split() ] rows = img_dims[0] columns = img_dims[1] if(len(img_dims) > 2): channels = img_dims[2] # Read the raw bytes. inputBytes = bytearray(inputFile.read()) # Build the image # # REPLACE THIS WITH YOUR OWN CODE TO CONVERT THE 'inputBytes' ARRAY INTO AN IMAGE IN 'img'. startTime = time.time() if len(img_dims) > 2: img = np.empty( [rows,columns,channels], dtype=np.uint8 ) else: img = np.empty([rows, columns], dtype=np.uint8) byteIter = iter(inputBytes) # For debugging #f = open('debug_decoding.txt', 'w') #kf = open('output_codes.txt', 'w') # Initialize dictionary maxsize = 65536 dict_size = 256 d = initializeDictionary(dict_size) s = '' e = [] while(True): try: k = getnextcode(byteIter) # this is except StopIteration: break #kf.write(str(convertchar2num(k)) + '\n') #print(k) if( convertchar2num(k) == dict_size): d[convertnum2char(dict_size)] = s + s[0] dict_size += 1 elif(len(s) > 0): d[convertnum2char(dict_size)] = s + d[k][0] dict_size += 1 for q in d[k]: e.append(ord(q)) s = d[k] if(dict_size > maxsize): dict_size = 256 d = initializeDictionary(dict_size) i = 0 for y in range(rows): for x in range(columns): for c in range(channels): fp = 0 if(len(img_dims) > 2): #fp = getprediction(img,x,y,c,True) if(x > 0): fp = img[y,x-1,c] img[y,x,c] = fp + e[i] else: #fp = getprediction(img,x,y,0,False) if(x > 0): fp = img[y,x-1] img[y,x] = fp + e[i] i += 1 endTime = time.time() # Output the image netpbm.imsave( outputFile, img ) sys.stderr.write( 'Uncompression time: %.2f seconds\n' % (endTime - startTime) )
def uncompress(inputFile, outputFile): # Check that it's a known file if inputFile.readline() != headerText + '\n': sys.stderr.write("Input is not in the '%s' format.\n" % headerText) sys.exit(1) # Read the rows, columns, and channels. list = [] # Read the rows, columns, and channels. list = [int(x) for x in inputFile.readline().split()] if len(list) == 3: rows = list[0] columns = list[1] channels = list[2] #if len(list) == 2: else: rows = list[0] columns = list[1] #else: #rows, columns, channels = [int(x) for x in inputFile.readline().split()] # Read the raw bytes. inputBytes = bytearray(inputFile.read()) # Build the image # # REPLACE THIS WITH YOUR OWN CODE TO CONVERT THE 'inputBytes' ARRAY INTO AN IMAGE IN 'img'. startTime = time.time() img = np.empty([rows, columns], dtype=np.uint8) try: while True: byteIter = iter(inputBytes) for y in range(rows): for x in range(columns): val1 = byteIter.next() val2 = byteIter.next() tup = (val1, val2) img[x, y] = pack(tup) # delimiter when we have the dictionary except StopIteration: pass # delimiter when we have the dictionary codeDict = genDict() print("YOLLAAA : " + str(img[0, 0])) old = img[0, 0] old_trans = codeDict[str(img[0, 0])] # loop print(img[0, 0]) for y in range(rows): for x in range(columns): for c in range(channels): new = img[x, y, c] if str(new) not in codeDict: s = old_trans s = str(s) + str(c) else: s = codeDict[str(new)] #print("THE S: " + str(s)) c = int(str(s)[:1]) codeDict[str(len(codeDict) + 1)] = int(str(old) + str(c)) old = new #print(str(codeDict)) print(str(len(codeDict))) endTime = time.time() # Output the image netpbm.imsave(outputFile, img) sys.stderr.write('Uncompression time: %.2f seconds\n' % (endTime - startTime))
def uncompress(inputFile, outputFile): # Check that it's a known file if inputFile.readline() != headerText + '\n': sys.stderr.write("Input is not in the '%s' format.\n" % headerText) sys.exit(1) # Read the rows, columns, and channels. rows, columns, channels = [int(x) for x in inputFile.readline().split()] # Read the raw bytes. inputBytes = bytearray(inputFile.read()) # Build the image # # REPLACE THIS WITH YOUR OWN CODE TO CONVERT THE 'inputBytes' ARRAY INTO AN IMAGE IN 'img'. startTime = time.time() def toInt(): try: first = next(byteIter) second = next(byteIter) output = (first << 8) | second except StopIteration: output = -1 return output img = np.empty([rows, columns, channels], dtype=np.uint8) byteIter = iter(inputBytes) init_dict = {} dict_size = (255 * 2) for i in range(dict_size + 1): init_dict[i] = str(i - 255) + "," # initialize all possible diffrences dict_copy = init_dict.copy() diff_image = [] prev_key = toInt() prev_val = dict_copy[prev_key].split(",")[:-1] diff_image += prev_val current_key = 0 while current_key != -1: if dict_size >= 65536: dict_copy = init_dict.copy() dict_size = (255 * 2) current_key = toInt() if current_key == -1: break # no next value found, exit loop if not current_key in dict_copy: prev_val += [prev_val[0]] diff_image += prev_val dict_size += 1 dict_copy[dict_size] = ",".join(prev_val) + "," else: current_val = dict_copy[current_key].split(",")[:-1] diff_image += current_val dict_size += 1 dict_copy[dict_size] = ",".join(prev_val + [current_val[0]]) + "," prev_val = current_val index = 0 if channels != 3: img = np.empty([rows, columns], dtype=np.uint8) for y in range(rows): img[y][0] = int(diff_image[index]) index += 1 for x in range(1, columns): img[y][x] = int(diff_image[index]) + img[y][x - 1] index += 1 else: for y in range(rows): for c in range(channels): img[y][0][c] = int(diff_image[index]) index += 1 for x in range(1, columns): for c in range(channels): img[y][x][c] = int(diff_image[index]) + img[y][x - 1][c] index += 1 endTime = time.time() # Output the image netpbm.imsave(outputFile, img) sys.stderr.write('Uncompression time: %.2f seconds\n' % (endTime - startTime))
#!/usr/bin/python2 import netpbm import os import numpy as np load_directory = "centroids/" save_directory = "centroid_images/" files = os.listdir(load_directory) for file in files: data = np.load(load_directory + file).astype(np.int64) netpbm.imsave(save_directory + file + ".pgm", data)
def uncompress(inputFile, outputFile): # Check that it's a known file if inputFile.readline() != headerText + '\n': sys.stderr.write("Input is not in the '%s' format.\n" % headerText) sys.exit(1) # Read the rows, columns, and channels. rows, columns, channels = [int(x) for x in inputFile.readline().split()] # Read the raw bytes. inputBytes = bytearray(inputFile.read()) # Build the image # # REPLACE THIS WITH YOUR OWN CODE TO CONVERT THE 'inputBytes' ARRAY INTO AN IMAGE IN 'img'. startTime = time.time() img = np.empty([rows, columns, channels], dtype=np.uint8) byteIter = iter(inputBytes) index = 256 # build initial dict similar to before dictionary = dict((i, chr(i)) for i in xrange(index)) difs = [] code = int(byteIter.next()) + int(byteIter.next()) * 256 S = dictionary[code] # decompress LMV while (len(inputBytes) > 0): code = int(inputBytes.pop(0)) + int(inputBytes.pop(0)) * 256 if code in dictionary: T = dictionary[code] elif code == index: T = T + T[0] # add the decoded difference for t in T: difs.append(struct.unpack('b', t)[0]) dictionary[index] = S + T[0] index += 1 S = T # debug to compare to original list of differences decoded = open('decoded.txt', 'w') for d in difs: decoded.write(str(d) + '\n') decoded.close() # go through each pixel in image and use difs to decode for y in range(rows): for x in range(1, columns): for c in range(channels): if len(difs) == 0: break if (channels == 1): # single channel img[y, x] = img[y, x - 1] + int(difs.pop(0)) else: img[y, x, c] = img[y, x - 1, c] + int(difs.pop(0)) endTime = time.time() # Output the image netpbm.imsave(outputFile, img) sys.stderr.write('Uncompression time: %.2f seconds\n' % (endTime - startTime))
def uncompress(inputFile, outputFile): # Check that it's a known file if inputFile.readline() != headerText + '\n': sys.stderr.write("Input is not in the '%s' format.\n" % headerText) sys.exit(1) # Read the rows, columns, and channels. line = [] line = [int(x) for x in inputFile.readline().split()] rows = int(line[0]) columns = int(line[1]) if len(line) == 3: channels = 3 else: channels = 1 # Read the raw bytes. inputBytes = bytearray(inputFile.read()) # Build the image # # REPLACE THIS WITH YOUR OWN CODE TO CONVERT THE 'inputBytes' ARRAY INTO AN IMAGE IN 'img'. startTime = time.time() img = np.empty([rows, columns, channels], dtype=np.uint8) baseDict = {} for i in range(512): baseDict[i] = str(i) + ',' byteIterator = iter(inputBytes) fileValues = [] for i in range(len(inputBytes) // 2 - 1): fileValues.append( int(byteIterator.next() << 8) + int(byteIterator.next())) s = baseDict[fileValues.pop(0)] output = s nextIndex = len(baseDict) for val in fileValues: if val in baseDict: t = baseDict[val] else: t = s + s.split(',')[0] + ',' output += t baseDict[nextIndex] = s + t.split(',')[0] + ',' s = t nextIndex += 1 output = output.split(',') output.pop(-1) for i in range(1, len(output)): output[i] += output[i - 1] i = 0 if (channels == 3): for num in output: x = i // (columns * channels) % channels y = i // channels % columns c = i % channels img[x, y, c] = num i += 1 else: for num in output: x = i // columns y = i % columns img[x, y] = num i += 1 endTime = time.time() # Output the image netpbm.imsave(outputFile, img) sys.stderr.write('Uncompression time: %.2f seconds\n' % (endTime - startTime))
def uncompress(inputFile, outputFile): # Check that it's a known file if inputFile.readline() != headerText + '\n': sys.stderr.write("Input is not in the '%s' format.\n" % headerText) sys.exit(1) # Read the rows, columns, and channels. rows, columns, channels = [int(x) for x in inputFile.readline().split()] # Read the raw bytes. inputBytes = bytearray(inputFile.read()) # Build the image # # REPLACE THIS WITH YOUR OWN CODE TO CONVERT THE 'inputBytes' ARRAY INTO AN IMAGE IN 'img'. startTime = time.time() img = np.empty([rows, columns, channels], dtype=np.uint8) byteIter = iter(inputBytes) for channel in range(channels): # initialize counter variable and lzw dictionary prevP = 0 lzwD, i = initLZWD() # reverse mapping lzwD = {v: k for k, v in lzwD.iteritems()} # read sequence from inputBytes and build index to look up in lzw dictionary bigB = byteIter.next() smallB = byteIter.next() lzwI = bigB * 256 + smallB # get first sequence S = lzwD[lzwI] img[0, 0, channel] = S[0] prevP = S[0] x = 0 y = 1 # while there are codes to decode while x < rows and y < columns: try: bigB = byteIter.next() smallB = byteIter.next() except StopIteration: print("no more data in bitstream") lzwI = bigB * 256 + smallB # check if end of lzwI if lzwI == 65535: break # search for T if lzwI in lzwD: T = lzwD[lzwI] # case when value is encoded as is else: T = S + (S[0], ) # write T to the image for byte in T: decodedP = prevP + byte img[x, y, channel] = decodedP prevP = decodedP y += 1 if y == columns: y = 0 x += 1 # stop at image borders to stop overflow if (x > rows and y > columns): break # add S to decode dict with T lzwD[i] = S + (T[0], ) i += 1 S = T # keep iterating until channel has ended while lzwI < 65535: try: bigB = byteIter.next() smallB = byteIter.next() except StopIteration: print("no more data in bitstream") break lzwI = bigB * 256 + smallB endTime = time.time() # Output the image netpbm.imsave(outputFile, img) sys.stderr.write('Uncompression time: %.2f seconds\n' % (endTime - startTime))
def uncompress(inputFile, outputFile): # Check that it's a known file if inputFile.readline() != headerText + '\n': sys.stderr.write("Input is not in the '%s' format.\n" % headerText) sys.exit(1) # Read the rows, columns, and channels. rows, columns, channels = [int(x) for x in inputFile.readline().split()] # Read the raw bytes. inputBytes = bytearray(inputFile.read()) # Build the image # # REPLACE THIS WITH YOUR OWN CODE TO CONVERT THE 'inputBytes' ARRAY INTO AN IMAGE IN 'img'. startTime = time.time() img = np.empty([rows, columns, channels], dtype=np.uint8) byteIter = iter(inputBytes) # For debugging f = open('debug_decoding.txt', 'w') # Initialize dictionary maxsize = 65536 i = 256 d = initializeDictionary(i) oldcode = str(getnextcode(byteIter)) f.write(oldcode) ch = oldcode while (True): newcode = str(getnextcode(byteIter)) if (newcode not in d): s = str(d[oldcode]) s += ch else: s = str(d[newcode]) f.write(s) ch = s[0] d[oldcode + ch] = i i += 1 oldcode = newcode # for y in range(rows): # for x in range(columns): # for c in range(channels): # k = getnextcode(byteIter) # #f.write(str(k)) # if( k > i ) : # return # if ( k == i ) : # special case # d[str(i)] = s + s[0] # i += 1 # elif ( s != "") : # d[str(i)] = s + str(d[str(k)])[0] # i += 1 # # write dictionary[k] to DF # f.write(str(d[str(k)])) # # S = dictionary[k] # s = str(d[str(k)]) # if(i > maxsize): # i = 256 # d = initializeDictionary(i) #fp = 0; #if(x > 0) : # fp = img[y,x-1,c] #img[y,x,c] = fp + e endTime = time.time() f.close() # Output the image netpbm.imsave(outputFile, img) sys.stderr.write('Uncompression time: %.2f seconds\n' % (endTime - startTime))
def uncompress( inputFile, outputFile ): # Check that it's a known file if inputFile.readline() != headerText + '\n': sys.stderr.write( "Input is not in the '%s' format.\n" % headerText ) sys.exit(1) # Read the rows, columns, and channels. rows, columns, channels = [ int(x) for x in inputFile.readline().split() ] # print inputBytes # Build the image # # REPLACE THIS WITH YOUR OWN CODE TO CONVERT THE 'inputBytes' ARRAY INTO AN IMAGE IN 'img'. inputBytes = bytearray(inputFile.read()) inputlen = len(inputBytes)/2 startTime = time.time() result = [] dictionary = {} dictsize = 0 for i in range(-255, 256): dictionary[dictsize] = [i] dictsize += 1 img = np.empty( [rows,columns,channels], dtype=np.uint8 ) byteIter = iter(inputBytes) currentbyte = byteIter.next() nextbyte = byteIter.next() phrase = (nextbyte << 8) + currentbyte lastStr = dictionary[phrase] result.append(lastStr) for i in range(1, inputlen): # again reset the dictionary if it reaches the limit if dictsize >= 65536: dictionary = {} # create a dictionary dictsize = 0 # pre-fill dictionary with single characters for i in range(-255, 256): dictionary[dictsize] = [i] dictsize += 1 currentbyte = byteIter.next() nextbyte = byteIter.next() phrase = (nextbyte << 8) + currentbyte if phrase in dictionary: entry = dictionary[phrase] else: entry = [] for j in lastStr: entry.append(j) entry.append(lastStr[0]) temp = [] for j in lastStr: temp.append(j) temp.append(lastStr[0]) dictionary[dictsize] = temp dictsize += 1 for k in range(len(entry)): result.append(entry[k]) lastStr = entry imgSize = rows*columns*channels counter = 1 for y in range(rows): for x in range(columns): for c in range(channels): if (counter < len(result)): img[y,x,c] = result[counter] counter += 1 endTime = time.time() netpbm.imsave( outputFile, img ) sys.stderr.write( 'Uncompression time: %.2f seconds\n' % (endTime - startTime) )