Пример #1
0
def encodeImage(path, scanningtype):
	img1 = Image.open(path)
	orgimg = list(img1.getdata(0))
	encodedimg = RLE.encodeImage(orgimg, img1.size[0], img1.size[1], img1.mode, scanningtype)
	tempimg = Detail(encodedimg, 1, img1.size[0], img1.size[1], img1.mode, scanningtype, img1.getpalette())
	compsize, filepath = RLE.saveCompressedToFile(tempimg, path)
	print("Encoded file saved to: " + filepath)
Пример #2
0
def encodeImage(path, scanningtype):
    img1 = Image.open(path)
    orgimg = list(img1.getdata(0))
    encodedimg = RLE.encodeImage(orgimg, img1.size[0], img1.size[1], img1.mode,
                                 scanningtype)
    tempimg = Detail(encodedimg, 1, img1.size[0], img1.size[1], img1.mode,
                     scanningtype, img1.getpalette())
    compsize, filepath = RLE.saveCompressedToFile(tempimg, path)
    print("Encoded file saved to: " + filepath)
Пример #3
0
def decodeImage(path):
	compimg = RLE.openFileToCompressed(path)
	decodedimg = RLE.decodeImage(compimg.compressed, compimg.width, compimg.height, compimg.mode, compimg.scanning)
	newimage = Image.new(compimg.mode, (compimg.width, compimg.height))
	newimage.putdata(decodedimg)
	if compimg.mode == 'P':
		newimage.putpalette(compimg.palette)
	newfilepath = path[:len(path) - 9] + "-copy.bmp"
	newimage.save(newfilepath)
	print("Decoded file saved to: " + newfilepath)
Пример #4
0
def encode_image(path, scan_type):
    image = Image.open(path)
    original_image = list(image.getdata(0))
    encoded_image = RLE.encode_image(original_image, image.size[0],
                                     image.size[1], image.mode, scan_type)
    temp_image = Detail(encoded_image, 1, image.size[0], image.size[1],
                        image.mode, scan_type, image.getpalette())
    compression_size, file_path = RLE.save_compressed_to_a_file(
        temp_image, path, scan_type)
    print("Encoded file saved to: " + file_path)
Пример #5
0
def decodeImage(path):
    compimg = RLE.openFileToCompressed(path)
    decodedimg = RLE.decodeImage(compimg.compressed, compimg.width,
                                 compimg.height, compimg.mode,
                                 compimg.scanning)
    newimage = Image.new(compimg.mode, (compimg.width, compimg.height))
    newimage.putdata(decodedimg)
    if compimg.mode == 'P':
        newimage.putpalette(compimg.palette)
    newfilepath = path[:len(path) - 9] + "-copy.bmp"
    newimage.save(newfilepath)
    print("Decoded file saved to: " + newfilepath)
Пример #6
0
 def test_compress_end_w_single(self):
     """ Compress array that ends with single and
     before it has sequence of identical values """
     orig_array = [129, 129, 129, 255]
     actual = RLE.compress(orig_array)
     expected = [129, 129, 0, 255]
     self.assertEqual(actual, expected)
Пример #7
0
 def test_compress_start_w_single(self):
     """ Compress array that starts with single and
     then has sequence of identical values """
     orig_array = [200, 0, 0]
     actual = RLE.compress(orig_array)
     expected = [0, 200, 128, 0]
     self.assertEqual(actual, expected)
Пример #8
0
 def test_decompress_mixed_sequence2(self):
     """ Decompress array that starts with seq of different elements
     and then has sequnce of identical elements """
     orig_array = [0, 1, 128, 128]
     actual = RLE.decompress(orig_array)
     expected = [1, 128, 128]
     self.assertEqual(actual, expected)
Пример #9
0
 def test_decompress_mixed_sequence1(self):
     """ Decompress array that stars with seq of identical elements
     then has sequnce of different element """
     orig_array = [128, 255, 3, 0, 255, 0, 255]
     actual = RLE.decompress(orig_array)
     expected = [255, 255, 0, 255, 0, 255]
     self.assertEqual(actual, expected)
 def RLEButtonAction(self):
     #inputString = self.inputString.get("1.0", tk.END)
     oldimagearray = self.convert_to_array()
     oldArrayFlattened = oldimagearray.flatten()
     #oldArrayFlattened = np.fromstring(inputString, sep=',', dtype=int)
     startTime = time.time()
     self.RLEoutput = RLE.encode(oldArrayFlattened)
     endTime = time.time()
     oldArrayFlattened = oldArrayFlattened.astype(np.uint16)
     compressionRatio = self.compressionRatio(
         sys.getsizeof(self.RLEoutput), sys.getsizeof(oldArrayFlattened))
     print("-----------------------------------------------------------")
     print("Run Length Encoding 1D array Size: ")
     print(sys.getsizeof(self.RLEoutput))
     print("Encoded array type:")
     print(self.RLEoutput.dtype)
     print("Original Image 1D array size: ")
     print(sys.getsizeof(oldArrayFlattened))
     print("old array type:")
     print((oldArrayFlattened.dtype))
     print("Compression Ratio:")
     print(str(compressionRatio) + "%")
     print("Execution Time:")
     print(endTime - startTime)
     print("-----------------------------------------------------------")
Пример #11
0
 def test_compress_max_2_identical(self):
     """ Compress array that has max + 2 length (131) of identical elements
     Max sequence + sequence """
     orig_array = [255] * (RLE.max_seq_same + 2)
     actual = RLE.compress(orig_array)
     expected = [255, 255, 128, 255]
     self.assertEqual(actual, expected)
Пример #12
0
 def test_compress_mixed_sequence3(self):
     """ Compress array that starts with one sequence of identiacal elemets
     and then continues with another sequence of identiacal elemets """
     orig_array = [2, 2, 3, 3, 3]
     actual = RLE.compress(orig_array)
     expected = [128, 2, 129, 3]
     self.assertEqual(actual, expected)
Пример #13
0
 def test_decompress_mixed_sequence1(self):
     """ Decompress array that stars with seq of identical elements
     then has sequnce of different element """
     orig_array = [128, 255, 3, 0, 255, 0, 255]
     actual = RLE.decompress(orig_array)
     expected = [255, 255, 0, 255, 0, 255]
     self.assertEqual(actual, expected)
Пример #14
0
 def test_compress_start_w_single(self):
     """ Compress array that starts with single and
     then has sequence of identical values """
     orig_array = [200, 0, 0]
     actual = RLE.compress(orig_array)
     expected = [0, 200, 128, 0]
     self.assertEqual(actual, expected)
Пример #15
0
 def test_decompress_mixed_sequence2(self):
     """ Decompress array that starts with seq of different elements
     and then has sequnce of identical elements """
     orig_array = [0, 1, 128, 128]
     actual = RLE.decompress(orig_array)
     expected = [1, 128, 128]
     self.assertEqual(actual, expected)
Пример #16
0
 def test_compress_mixed_sequence_complex(self):
     """ Compress array from example """
     orig_array = [0, 0, 0, 0, 0, 0, 4, 2, 0, 4, 4, 4, 4, 4, 4, 4,
     80, 80, 80, 80, 0, 2, 2, 2, 2, 255, 255, 255, 255, 255, 0, 0]
     actual = RLE.compress(orig_array)
     expected = [132, 0, 2, 4, 2, 0, 133, 4, 130, 80, 0, 0, 130, 2, 131, 255, 128, 0]
     self.assertEqual(actual, expected)
Пример #17
0
 def test_compress_end_w_single(self):
     """ Compress array that ends with single and
     before it has sequence of identical values """
     orig_array = [129, 129, 129, 255]
     actual = RLE.compress(orig_array)
     expected = [129, 129, 0, 255]
     self.assertEqual(actual, expected)
Пример #18
0
 def test_compress_max_1_identical(self):
     """ Compress array that has max + 1 length (130) of identical elements
     Max sequence + single """
     orig_array = [0] * (RLE.max_seq_same + 1)
     actual = RLE.compress(orig_array)
     expected = [255, 0, 0, 0]
     self.assertEqual(actual, expected)
Пример #19
0
 def test_compress_mixed_sequence3(self):
     """ Compress array that starts with one sequence of identiacal elemets
     and then continues with another sequence of identiacal elemets """
     orig_array = [2, 2, 3, 3, 3]
     actual = RLE.compress(orig_array)
     expected = [128, 2, 129, 3]
     self.assertEqual(actual, expected)
Пример #20
0
 def test_compress_max_1_identical(self):
     """ Compress array that has max + 1 length (130) of identical elements
     Max sequence + single """
     orig_array = [0] * (RLE.max_seq_same + 1)
     actual = RLE.compress(orig_array)
     expected = [255, 0, 0, 0]
     self.assertEqual(actual, expected)
Пример #21
0
def decode_image(path):
    compressed_image = RLE.open_file_to_compressed(path)
    decoded_image = RLE.decode_image(compressed_image.compressed,
                                     compressed_image.width,
                                     compressed_image.height,
                                     compressed_image.mode,
                                     compressed_image.scanning)
    new_image = Image.new(compressed_image.mode,
                          (compressed_image.width, compressed_image.height))
    new_image.putdata(decoded_image)
    if compressed_image.mode == 'P':
        new_image.putpalette(compressed_image.palette)
    new_file_path = path[:len(path) - 9] + "-copy." + path.partition(
        ".")[2].partition(".")[0]
    new_image.save(new_file_path)
    print("Decoded file saved to: " + new_file_path)
Пример #22
0
 def test_compress_max_2_identical(self):
     """ Compress array that has max + 2 length (131) of identical elements
     Max sequence + sequence """
     orig_array = [255] * (RLE.max_seq_same + 2)
     actual = RLE.compress(orig_array)
     expected = [255, 255, 128, 255]
     self.assertEqual(actual, expected)
Пример #23
0
 def test_compress_1_max_different_and_sequence(self):
     """ Compress array that has max - 1 sequence(127) of different elements
     and then starts sequence of the same elemenents """
     orig_array = list(range(0, RLE.max_seq_diff - 1))
     orig_array += [1, 1]
     actual = RLE.compress(orig_array)
     expected = [126] + list(range(0, RLE.max_seq_diff - 1)) + [128, 1]
     self.assertEqual(actual, expected)
Пример #24
0
 def test_compress_max_identical(self):
     """ Compress array that has max length (129 = 127 + 2) of identical elements
     and single element after sequence """
     orig_array = [0] * RLE.max_seq_same
     orig_array += [1]
     actual = RLE.compress(orig_array)
     expected = [255, 0, 0, 1]
     self.assertEqual(actual, expected)
Пример #25
0
 def test_compress_mixed_sequence4(self):
     """ Compress array that starts with one sequence of identiacal elemets
     then has single different element and
     then continues with another sequence of identiacal elemets """
     orig_array = [5, 5, 5, 5, 5, 0, 3, 3, 3]
     actual = RLE.compress(orig_array)
     expected = [131, 5, 0, 0, 129, 3]
     self.assertEqual(actual, expected)
Пример #26
0
 def test_compress_max_different(self):
     """ Compress array that has max sequence (128 = 127 + 1) of different elements
     and sequence of identical elemenets after """
     orig_array = list(range(0, RLE.max_seq_diff))
     orig_array += [1, 1, 1, 1]
     actual = RLE.compress(orig_array)
     expected = [127] + list(range(0, RLE.max_seq_diff)) + [130, 1]
     self.assertEqual(actual, expected)
Пример #27
0
 def test_compress_max_different(self):
     """ Compress array that has max sequence (128 = 127 + 1) of different elements
     and sequence of identical elemenets after """
     orig_array = list(range(0, RLE.max_seq_diff))
     orig_array += [1, 1, 1, 1]
     actual = RLE.compress(orig_array)
     expected = [127] + list(range(0, RLE.max_seq_diff)) + [130, 1]
     self.assertEqual(actual, expected)
Пример #28
0
 def test_compress_1_max_different_and_sequence(self):
     """ Compress array that has max - 1 sequence(127) of different elements
     and then starts sequence of the same elemenents """
     orig_array = list(range(0, RLE.max_seq_diff - 1))
     orig_array += [1, 1]
     actual = RLE.compress(orig_array)
     expected = [126] + list(range(0, RLE.max_seq_diff - 1)) + [128, 1]
     self.assertEqual(actual, expected)
Пример #29
0
 def test_compress_mixed_sequence4(self):
     """ Compress array that starts with one sequence of identiacal elemets
     then has single different element and
     then continues with another sequence of identiacal elemets """
     orig_array = [5, 5, 5, 5, 5, 0, 3, 3, 3]
     actual = RLE.compress(orig_array)
     expected = [131, 5, 0, 0, 129, 3]
     self.assertEqual(actual, expected)
Пример #30
0
 def test_compress_max_1_identical_and_single(self):
     """ Compress array that has max + 1 length (130) of identical elements
     and one single element after """
     orig_array = [128] * (RLE.max_seq_same + 1)
     orig_array += [1]
     actual = RLE.compress(orig_array)
     expected = [255, 128, 1, 128, 1]
     self.assertEqual(actual, expected)
Пример #31
0
 def test_compress_max_1_identical_and_single(self):
     """ Compress array that has max + 1 length (130) of identical elements
     and one single element after """
     orig_array = [128] * (RLE.max_seq_same + 1)
     orig_array += [1]
     actual = RLE.compress(orig_array)
     expected = [255, 128, 1, 128, 1]
     self.assertEqual(actual, expected)
Пример #32
0
 def test_compress_max_identical(self):
     """ Compress array that has max length (129 = 127 + 2) of identical elements
     and single element after sequence """
     orig_array = [0] * RLE.max_seq_same
     orig_array += [1]
     actual = RLE.compress(orig_array)
     expected = [255, 0, 0, 1]
     self.assertEqual(actual, expected)
    def testGRY4BIT(self):
        imgdirname = "../images/4bit"

        filelist = glob.glob(imgdirname + "/*.bmp")
        for file in filelist:
            img1 = Image.open(file)

            orgimg = list(img1.getdata(0))
            print(file)
            for scanningmethod in self.scanningtypes:
                with timewith('4bit Number ' + scanningmethod) as timer:
                    encodedimg = RLE.encodeImage(orgimg, img1.size[0],
                                                 img1.size[1], img1.mode,
                                                 scanningmethod)
                    self.addNameToDictionary(
                        '4bit', scanningmethod, file, 'Encode',
                        timer.checkpoint('Encode Image Mode ' +
                                         scanningmethod + " " + file))

                    tempimg = Detail(encodedimg, 1, img1.size[0], img1.size[1],
                                     img1.mode, scanningmethod,
                                     img1.getpalette())
                    compsize, filepath = RLE.saveCompressedToFile(
                        tempimg, file)
                    statinfo = os.stat(file)
                    compimg = RLE.openFileToCompressed(file + ".comp")
                    self.addNameToDictionary(
                        '4bit', scanningmethod, file, 'Compression Ratio',
                        math.ceil((compsize / statinfo.st_size) * 1000) / 1000)
                    timer.checkpoint('Compression Ratio ' + scanningmethod +
                                     " " + file)

                    decodedimg = RLE.decodeImage(compimg.compressed,
                                                 compimg.width, compimg.height,
                                                 compimg.mode, scanningmethod)
                    self.addNameToDictionary(
                        '4bit', scanningmethod, file, 'Decode',
                        timer.checkpoint('Decode Image Mode ' +
                                         scanningmethod + " " + file))
                    self.addNameToDictionary('4bit', scanningmethod, file,
                                             'Equality',
                                             str(orgimg == decodedimg))
Пример #34
0
    def RLEButtonAction(self):
        oldimagearray = self.convert_to_array()
        oldArrayFlattened = oldimagearray.flatten()
        self.RLEoutput = RLE.encode(oldArrayFlattened)

        print("Run Length Encoding 1D array: ")
        print(self.RLEoutput)
        print("Run Length Encoding 1D array Size: ")
        print(sys.getsizeof(self.RLEoutput))
        print("Original Image 1D array size: ")
        print(sys.getsizeof(oldimagearray))
Пример #35
0
 def test_compress_mixed_sequence_complex(self):
     """ Compress array from example """
     orig_array = [
         0, 0, 0, 0, 0, 0, 4, 2, 0, 4, 4, 4, 4, 4, 4, 4, 80, 80, 80, 80, 0,
         2, 2, 2, 2, 255, 255, 255, 255, 255, 0, 0
     ]
     actual = RLE.compress(orig_array)
     expected = [
         132, 0, 2, 4, 2, 0, 133, 4, 130, 80, 0, 0, 130, 2, 131, 255, 128, 0
     ]
     self.assertEqual(actual, expected)
    def RLEDecodeButtonAction(self):
        oldimagearray = self.convert_to_array()
        startTime = time.time()
        decodedArray = RLE.decode(self.RLEoutput)
        endTime = time.time()
        #decodedArray2D = np.reshape(decodedArray, (-1, 2))
        #self.show_new_image(decodedArray2D, "RLE Decode")

        B = decodedArray.reshape((len(oldimagearray), len(oldimagearray[0])))
        print("-----------------------------------------------------------")
        print("Decode Time:")
        print(endTime - startTime)
        print("-----------------------------------------------------------")
        self.show_new_image(B, "RLE Decoded")
Пример #37
0
	def testGRY8BIT(self):
		imgdirname = "../images/8bit"

		filelist = glob.glob(imgdirname + "/*.bmp")
		for file in filelist:
			img1 = Image.open(file)

			orgimg = list(img1.getdata(0))

			for scanningmethod in self.scanningtypes:
				with timewith('8bit Number ' + scanningmethod) as timer:
					encodedimg = RLE.encodeImage(orgimg, img1.size[0], img1.size[1], img1.mode, scanningmethod)
					self.addNameToDictionary('8bit', scanningmethod, file, 'Encode', timer.checkpoint('Encode Image Mode ' + scanningmethod + " " + file))

					tempimg = Detail(encodedimg, 1, img1.size[0], img1.size[1], img1.mode, scanningmethod)
					compsize, filepath = RLE.saveCompressedToFile(tempimg, file)
					statinfo = os.stat(file)
					compimg = RLE.openFileToCompressed(file + ".comp")
					self.addNameToDictionary('8bit', scanningmethod, file, 'Compression Ratio', math.ceil((compsize / statinfo.st_size) * 1000) / 1000)
					timer.checkpoint('Compression Ratio ' + scanningmethod + " " + file)

					decodedimg = RLE.decodeImage(compimg.compressed, compimg.width, compimg.height, compimg.mode, scanningmethod)
					self.addNameToDictionary('8bit', scanningmethod, file, 'Decode', timer.checkpoint('Decode Image Mode ' + scanningmethod + " " + file))
					self.addNameToDictionary('8bit', scanningmethod, file, 'Equality', str(orgimg == decodedimg))
Пример #38
0
def decode(encodedList):
    result = []
    for i in range(8):
        tmp = list(RLE.decode(np.asarray(encodedList[i], dtype=int)))
        result.append(tmp)
    resultDecoded = []
    tmp = []
    for i in range(len(result[0])):
        for j in range(8):
            tmp.append(result[j][i])
        resultDecoded.append(tmp)
        tmp = []
    resultFinished = []
    for i in range(len(resultDecoded)):
        tmp = resultDecoded[i]
        num = ''.join(map(str, tmp))
        resultFinished.append(int(num, 2))

    return resultFinished
Пример #39
0
def encode(oldArrayFlattened):
    # result will lead with 0 bit plane
    result = []
    binaryOldArray = []
    # convert original numbers to 8 bit binary
    for i in range(len(oldArrayFlattened)):
        binaryOldArray.append(format(oldArrayFlattened[i], '08b'))

    bitPlane = []

    for i in range(8):
        for j in range(len(binaryOldArray)):
            bitPlane.append(binaryOldArray[j][i])
        result.append(bitPlane)
        bitPlane = []

    result = np.asarray(result, dtype=int)
    resultEncoded = []
    for i in range(8):
        tmp = result[i]
        tmpEncoded = RLE.encode(tmp)
        resultEncoded.append(list(tmpEncoded))

    return resultEncoded
Пример #40
0
    output_file.write(texto_generado)
    output_file.close()
    #calculo de tamaño
    file = Path('Texto_generado'+str(i)+".txt") # or Path('./doc.txt')
    size1 = file.stat().st_size
    #Calculo de información y entropía
    datos=Formulas_shannon.Datos_shannon(size1,cdad_simbolos) #información,entropia
    #para la tabla
    archivo.append(str(i))
    tamaño_1.append(size1)
    informacion_1.append(datos[0])
    entropia_1.append(datos[1])

    #COMPRESION RLE
    start_time = time()
    texto_comprimido=RLE.encode("Texto_generado"+str(i)+".txt","Texto_generado_RLE"+str(i)+".txt")
    elapsed_time = time() - start_time
    file = Path('Texto_generado_RLE'+str(i)+".txt") # or Path('./doc.txt')
    size2 = file.stat().st_size
    #Calculo de información y entropía
    datos=Formulas_shannon.Datos_shannon(size2,cdad_simbolos) #información,entropia
    #para la tabla
    tamaño_2.append(size2)
    tiempo.append(elapsed_time)
    informacion_2.append(datos[0])
    entropia_2.append(datos[1])
    Tabla.append([archivo[i-1],tamaño_1[i-1],tamaño_2[i-1],tiempo[i-1],informacion_1[i-1],informacion_2[i-1],entropia_1[i-1],entropia_2[i-1]])

    #DESCOMPRESION RLE
    start_time = time()
    texto_descomprimido=RLE.decode("Texto_generado_RLE"+str(i)+".txt","Texto_generado_RLE_decode"+str(i)+".txt")
Пример #41
0
 def test_compress_single_element(self):
     """ Compress array that has only different values """
     orig_array = [100]
     actual = RLE.compress(orig_array)
     expected = [0, 100]
     self.assertEqual(actual, expected)
Пример #42
0
 def test_compress_max_1_different(self):
     """ Compress array that has max + 1 sequence(129) of different elements """
     orig_array = list(range(0, RLE.max_seq_diff + 1))
     actual = RLE.compress(orig_array)
     expected = [127] + list(range(0, RLE.max_seq_diff)) + [0, 128]
     self.assertEqual(actual, expected)
Пример #43
0
 def test_compress_only_identical(self):
     """ Compress array that has only identical values """
     orig_array = [0, 0, 0]
     actual = RLE.compress(orig_array)
     expected = [129, 0]
     self.assertEqual(actual, expected)
Пример #44
0
 def test_compress_only_identical(self):
     """ Compress array that has only identical values """
     orig_array = [0, 0, 0]
     actual = RLE.compress(orig_array)
     expected = [129, 0]
     self.assertEqual(actual, expected)
Пример #45
0
 def test_decompress_seq_diff(self):
     """ Decompress array that has only different elements """
     orig_array = [1, 0, 1]
     actual = RLE.decompress(orig_array)
     expected = [0, 1]
     self.assertEqual(actual, expected)
Пример #46
0
 def test_decompress_seq_identical(self):
     """ Decompress array that has only identical elements """
     orig_array = [128, 128]
     actual = RLE.decompress(orig_array)
     expected = [128, 128]
     self.assertEqual(actual, expected)
Пример #47
0
for idx, channel in enumerate(copy):
    rows, cols = channel.shape
    for row in range(0, rows, 8):
        for col in range(0, cols, 8):
            bloc = channel[row:row + 8, col:col + 8]
            flattenedBloc = bloc.flatten()
            fileContent.extend(flattenedBloc[Zigzag].tolist())

# huffman encoding
import huffman
filechars = "".join(map(lambda x: str(x) + ",", fileContent))
huffRes = huffman.encode(filechars)

# run length encoding
import RLE
rleRes = RLE.encode(huffRes)

# sizes
hsize = len(huffRes.tobytes())
rsize = int(len(rleRes) * 1.5 / 8)
print "original size = ", reduce(
    lambda x, y: x * y, image.shape
), " bytes, huffman size = ", hsize, "bytes, compressed size = ", rsize, " bytes"

# decoding
decoded = RLE.decode(rleRes)
decoded = eval("[" + huffman.decode(decoded)[:len(filechars)] + "]")

pointer = 0
final = np.zeros(image.shape, np.uint8)
for idx, channel in enumerate(copy):
Пример #48
0
 def test_compress_only_different(self):
     """ Compress array that has only different values """
     orig_array = [0, 1, 2]
     actual = RLE.compress(orig_array)
     expected = [2, 0, 1, 2]
     self.assertEqual(actual, expected)
Пример #49
0
 def test_compress_mixed_sequence1(self):
     """ Compress array that starts with the identical values and then has different values """
     orig_array = [255, 255, 0, 255, 0, 255]
     actual = RLE.compress(orig_array)
     expected = [128, 255, 3, 0, 255, 0, 255]
     self.assertEqual(actual, expected)
Пример #50
0
 def test_compress_mixed_sequence2(self):
     """ Compress array that starts different values and then has the identical values """
     orig_array = [1, 128, 128]
     actual = RLE.compress(orig_array)
     expected = [0, 1, 128, 128]
     self.assertEqual(actual, expected)
Пример #51
0
 def test_decompress_max_diff(self):
     """ Decompress array that has max sequence of different elements """
     orig_array = [127] + list(range(100, RLE.max_seq_diff + 100))
     actual = RLE.decompress(orig_array)
     expected = list(range(100, RLE.max_seq_diff + 100))
     self.assertEqual(actual, expected)
Пример #52
0
 def test_compress_mixed_sequence1(self):
     """ Compress array that starts with the identical values and then has different values """
     orig_array = [255, 255, 0, 255, 0, 255]
     actual = RLE.compress(orig_array)
     expected = [128, 255, 3, 0, 255, 0, 255]
     self.assertEqual(actual, expected)
Пример #53
0
#USAGE
# For encode: python RLE.py encode Codigo.txt RLE_encode.txt
# For decode: python RLE.py decode RLE_encode.txt RLE_decode.txt
import RLE
import sys
print("argumentos pasados", sys.argv)
action = sys.argv[1]  #encode o decode
input_file = sys.argv[2]  #input file
output_file = sys.argv[3]  #output file
if (action == "encode"):
    aux = RLE.encode(input_file, output_file)
if (action == "decode"):
    aux = RLE.decode(input_file, output_file)
Пример #54
0
 def test_decompress_1(self):
     """ Decompress array that has only 1 element """
     orig_array = [0, 255]
     actual = RLE.decompress(orig_array)
     expected = [255]
     self.assertEqual(actual, expected)
def benchmarks():

    print("BENCHMARK...")
    photonfilepath = '/home/nard/PhotonFile/test/bunny.cbddlp'
    photonfile = PhotonFile(photonfilepath)
    photonfile.load()
    n = 50

    print()
    print(" UNITS...")

    #PIL.Image.open
    imgfilepath = '/home/nard/PhotonFile/test/images/test.png'
    t = time.time()
    for i in range(0, n):
        im = PIL.Image.open(imgfilepath)
        nparr = numpy.asarray(im)
    d = (time.time() - t) / n
    print(f"  PIL.Image.open x 1000        : {round(1000*d,2)} sec")

    #cv2.imread
    imgfilepath = '/home/nard/PhotonFile/test/images/test.png'
    t = time.time()
    for i in range(0, n):
        im = cv2.imread(imgfilepath)
        nparr = im
    d = (time.time() - t) / n
    print(f"  cv2.imread x 1000            : {round(1000*d,2)} sec")

    #PIL.Image.save (comp level = 3 is fastest)
    imgfilepath = '/home/nard/PhotonFile/test/images/test.png'
    imgfilepath_new = '/home/nard/PhotonFile/test/images/test_save2pil.png'
    im = PIL.Image.open(imgfilepath)
    t = time.time()
    for i in range(0, n):
        im.save(imgfilepath_new, compress_level=3)
    d = (time.time() - t) / n
    print(f"  PIL.Image.save(comp=6) x 1000: {round(1000*d,2)} sec")

    #CV.imwrite
    imgfilepath = '/home/nard/PhotonFile/test/images/test.png'
    imgfilepath_new = '/home/nard/PhotonFile/test/images/test_save2cv2.png'
    img = cv2.imread(imgfilepath, -1)
    t = time.time()
    for i in range(0, n):
        cv2.imwrite(imgfilepath_new, img)
        #cv2.imwrite(imgfilepath_new,img,[int(cv2.IMWRITE_PNG_COMPRESSION), 1])
    d = (time.time() - t) / n
    print(f"  CV2.Image.write x 1000       : {round(1000*d,2)} sec")

    #PIL.Image -> Numpy 1D
    t = time.time()
    for i in range(0, n):
        np = numpy.asarray(im)
        if np.ndim == 3: np = np[:, :, 0]
        npf = np.flatten()
    d = (time.time() - t) / n
    print(f"  PIL.Image -> Numpy 1D x 1000 : {round(1000*d,2)} sec")

    #cv2.Image -> Numpy 1D
    t = time.time()
    for i in range(0, n):
        np = numpy.array(img)
        if np.ndim == 3: np = np[:, :, 0]
        npf = np.flatten()
    d = (time.time() - t) / n
    print(f"  CV2.Image -> Numpy 1D x 1000 : {round(1000*d,2)} sec")

    #decodeRLE
    rleData = photonfile.layers.get(3, retType='rle')
    t = time.time()
    for i in range(0, n):
        nparr = RLE.decodeRLE28bImage(rleData)
    d = (time.time() - t) / n
    print(f"  RLE.decodeRLE28bImage x 1000 : {round(1000*d,2)} sec")

    #encodeRLE
    t = time.time()
    for i in range(0, n):
        rleData = RLE.encode8bImage2RLE(npf)
    d = (time.time() - t) / n
    print(f"  RLE.encode8bImage2RLE x 1000 : {round(1000*d,2)} sec")

    #get nrpixels
    rleData = photonfile.layers.get(4, retType='rle')
    t = time.time()
    for i in range(0, n):
        pixelsInLayer = RLE.RLEPixels(rleData)
    d = (time.time() - t) / n
    print(f"  RLE.RLEPixels x 1000         : {round(1000*d,2)} sec")

    #get rle bytes
    t = time.time()
    for i in range(0, n):
        rleData = photonfile.layers.get(4, 'rle')
    d = (time.time() - t) / n
    print(f"  layers.get(4,'rle') x 1000   : {round(1000*d,2)} sec")

    #get numpy bytes
    t = time.time()
    for i in range(0, n):
        numpy2D = photonfile.layers.get(4, retType='numpy')
    d = (time.time() - t) / n
    print(f"  layers.get(4,'numpy') x 1000 : {round(1000*d,2)} sec")

    #get volume
    t = time.time()
    for i in range(0, n):
        numpy2D = photonfile.volume()
    d = (time.time() - t) / n
    print(f"  photonfile.volume() x 1      : {round(d,2)} sec")

    print()
    print(" EXPORT/IMPORT...")

    #export image from rle data in layer using PIL.Image.save
    imgfilepath_new = '/home/nard/PhotonFile/test/images/test_export2pil.png'
    t = time.time()
    for i in range(0, n):
        rleData = photonfile.layers.get(3, retType='rle')
        numpyArray1Duint8 = RLE.decodeRLE28bImage(rleData)
        numpyArray2Duint8 = numpyArray1Duint8.reshape(2560, 1440)
        im = PIL.Image.fromarray(numpyArray2Duint8)
        im.save(imgfilepath_new, compress_level=3)
    d = (time.time() - t) / n
    print(f"  RLE->PIL.Image.save x 1000   : {round(1000*d,2)} sec")

    #export image from rle data in layer using CV2.imwrite
    imgfilepath_new = '/home/nard/PhotonFile/test/images/test_export2cv2.png'
    t = time.time()
    for i in range(0, n):
        rleData = photonfile.layers.get(3, retType='rle')
        numpyArray1Duint8 = RLE.decodeRLE28bImage(rleData)
        numpyArray2Duint8 = numpyArray1Duint8.reshape(2560, 1440, 1)
        cv2.imwrite(imgfilepath_new, numpyArray2Duint8)
    d = (time.time() - t) / n
    print(f"  RLE->CV2.Image.write x 1000  : {round(1000*d,2)} sec")

    #import image from rle data in layer using PIL.Image.open
    imgfilepath_new = '/home/nard/PhotonFile/test/images/test.png'
    t = time.time()
    for i in range(0, n):
        im = PIL.Image.open(imgfilepath_new)
        npArray = numpy.asarray(im)
        if npArray.ndim == 3:
            npArray = npArray[:, :, 0]
        npArray = npArray.flatten()
        rleData = RLE.encode8bImage2RLE(npArray)
    d = (time.time() - t) / n
    imgfilepath_chk = '/home/nard/PhotonFile/test/images/test_checkload_pil.png'
    numpyArray1Duint8 = RLE.decodeRLE28bImage(rleData)
    numpyArray2Duint8 = numpyArray1Duint8.reshape(2560, 1440)
    im = PIL.Image.fromarray(numpyArray2Duint8)
    im.save(imgfilepath_chk, compress_level=3)
    print(f"  PIL.Image.open->RLE x 1000   : {round(1000*d,2)} sec")

    #import image from rle data in layer using CV2.imread
    imgfilepath_new = '/home/nard/PhotonFile/test/images/test.png'
    t = time.time()
    for i in range(0, n):
        npArray = cv2.imread(imgfilepath_new,
                             cv2.IMREAD_UNCHANGED)  # is native numpy array
        if npArray.ndim == 3:
            npArray = npArray[:, :, 0]
        npArray = npArray.flatten()
        rleData = RLE.encode8bImage2RLE(npArray)
    d = (time.time() - t) / n
    imgfilepath_chk = '/home/nard/PhotonFile/test/images/test_checkload_cv2.png'
    numpyArray1Duint8 = RLE.decodeRLE28bImage(rleData)
    numpyArray2Duint8 = numpyArray1Duint8.reshape(2560, 1440, 1)
    cv2.imwrite(imgfilepath_chk, numpyArray2Duint8)
    print(f"  CV2.imread->RLE x 1000       : {round(1000*d,2)} sec")
Пример #56
0
 def test_compress_mixed_sequence2(self):
     """ Compress array that starts different values and then has the identical values """
     orig_array = [1, 128, 128]
     actual = RLE.compress(orig_array)
     expected = [0, 1, 128, 128]
     self.assertEqual(actual, expected)
Пример #57
0
 def test_decompress_max_identical(self):
     """ Decompress array that has max sequence of identical elements """
     orig_array = [255, 255]
     actual = RLE.decompress(orig_array)
     expected = [255] * RLE.max_seq_same
     self.assertEqual(actual, expected)