Пример #1
0
def tabulate_search(points, seq_provider, args, out):

    codec = codecs()[args.codec]()
    results = [None for _ in range(len(points))]
    table = Table(80, lambda x: util.log(x, out))

    table.print_line("=")
    table.print("#.",
                "Resolution",
                "Frames",
                "Threshold",
                lengths=[5, 20, 20, 35])
    table.print_line("=")

    for i, point in enumerate(points):
        samples = []
        threshold = (None, None, None, None, None)
        for j in range(args.iterations):

            seqs = seq_provider(*point, val_range=args.range)
            table.print("Rate", "Resolution", "Frames", "bsize", "size")
            table.print_line("-")

            tab = tab_event_threshold(codec, args.entropy_coder, seqs,
                                      args.precision)
            threshold = get_threshold(tab, table)
            samples.append(threshold[2])

            table.print_line("=")
            table.print(f"{j+1}.", *threshold, lengths=[5, 20, 20, 35])
            table.print_line("=")

        results[i] = (threshold[0], threshold[1], np.mean(samples))
        table.print_line("*")
        table.print("avg:", *results[i], lengths=[5, 25, 25, 25])

        # Bootstrap for confidence interval
        B = 100000
        bsamples = np.random.choice(samples, (len(samples), B))
        bmeans = np.mean(bsamples, axis=0)
        bmeans.sort()
        bmean = np.mean(bmeans)
        conf_int = np.percentile(bmeans, [2.5, 97.5])
        table.print(f"Bootstrap mean: {bmean}")
        table.print(f"Confidence interval (95%): {conf_int}")
        table.print(f"Samples: {samples}")
        table.print_line("*")

    table.print("SUMMARY")
    table.print("Resolution", "Frames", "Threshold", lengths=[20, 20, 40])
    table.print_line("=")
    for i, point in enumerate(points):
        table.print(*results[i], lengths=[20, 20, 40])
    table.print_line("=")
Пример #2
0
def main():
    parser = util.get_parser(__file__)
    args = parser.parse_args()
    codec = codecs()[args.codec]

    with open(args.input, 'rb') as inp:
        with open(args.output, 'wb+') as out:
            if args.decompress:
                decompress(codec, inp, out)
            else:
                frames = VideoSequence(inp)
                if args.grayscale:
                    frames = GrayscaleVideoConverter(frames)
                compress(codec, frames, inp, out)

            inp_size = os.path.getsize(inp.name)
            out_size = os.path.getsize(out.name)
            print(f"Compressed {inp_size} --> {out_size}")
Пример #3
0
def main():
    args = get_args()

    x = np.linspace(*args.range, args.samples)
    codec_names = ["raw", "short_aer", "residual"]
    codec_colors = ["k", "b", "r"]
    results = {name: [] for name in codec_names}

    for seq in sequences(x, args):
        for codec_name in codec_names:
            print(f"{codec_name}: ", end="", flush=True)
            codec = codecs()[codec_name]
            bytes_seq = functools.reduce(operator.add, codec.encoder(seq),
                                         bytearray())
            # Leave one, comment out the others
            #result = len(bytes_seq)
            #result = compute_entropy([bytes_seq])
            result = len(bytes_seq) * compute_entropy([bytes_seq])

            results[codec_name].append(result)
            print(result)
    print("SUMMARY:")
    print(f"x: {x}")
    print(f"y: {results}")
    print("")

    print("Plotting graphs...")
    for codec_name, color in zip(codec_names, codec_colors):
        plt.plot(x, results[codec_name], color, label=codec_name)

    plt.xlabel('Event Rate')

    # Comment out the same lines as previously
    #plt.ylabel('Bytes')
    #plt.ylabel('Entropy')
    plt.ylabel('Average Compressed Size (bytes)')

    plt.title(
        f"File sizes res:{args.res}, dur:{args.duration}, samples:{args.samples}"
    )
    plt.legend()

    plt.show()
Пример #4
0
def main():
    formats = codec.codecs()
    formats['raw'] = None  # Register additional format

    # Define script interface
    args = get_args()

    frame_iterator = get_frame_iterator(args)

    os.makedirs(os.path.dirname(args.out), exist_ok=True)
    with open(args.out, "wb+") as out:
        codec.util.create_raw_file(out, args.res, args.fps, args.duration)
        if args.format == 'raw':
            with tempfile.TemporaryDirectory() as tmpdirname:
                for i, frame in enumerate(frame_iterator):
                    codec.util.save_frame(out, frame)
                    Image.fromarray(
                        np.uint8(frame)).save(f'{tmpdirname}/img_{i}.pgm')
                os.system(
                    f"ffmpeg -f image2 -framerate 30 -i {tmpdirname}/img_%d.pgm -c:v libx264 -preset veryslow -crf 0 -pix_fmt gray {args.out}"
                )
        else:
            for chunk in formats[args.format].encoder(frame_iterator):
                out.write(chunk)
Пример #5
0
def test_init():
    assert codec.codecs()
Пример #6
0
import sys
import os
import argparse
import tempfile
from pathlib import Path
import event_compression.sequence as sequence
import event_compression.sequence.synthetic as synthetic
import event_compression.codec as codec
from event_compression.scripts import util
import pandas as pd
import os, sys

names = ["moving_edge", "single_color", "random_pixel", "checkers"]
formats = ["aer", "caer", "raw"]

codecs = codec.codecs()
sequences = sequence.sequences()

entropy_coder = sys.argv[1]


def entropy_compress(path, out_path):
	command = f"{entropy_coder} {path} {out_path}"
	print(f"Running: {command}")
	os.system(command)


def get_frame_iterator(name):
	sequence_config = synthetic.Config([32, 32],
	                                   30,
	                                   2,
Пример #7
0
        seq = RandomChange(seq_conf)
        yield seq


RESOLUTION = (32, 32)
DURATION = 30
x = np.linspace(0, 1, 100)
codec_names = ["raw", "short_aer", "residual"]
codec_colors = ["k", "b", "r"]
metrics = ["Entropy", "Size", "Compressed Size"]
results = {metric: {name: [] for name in codec_names} for metric in metrics}

for seq in sequences(x, RESOLUTION, DURATION):
    for codec_name in codec_names:
        print(f"{codec_name}: ", end="", flush=True)
        codec = codecs()[codec_name]
        bytes_seq = functools.reduce(operator.add, codec.encoder(seq),
                                     bytearray())
        # Leave one, comment out the others
        size = len(bytes_seq)
        entropy = compute_entropy([bytes_seq])
        entropy_size = size * entropy

        results["Size"][codec_name].append(size)
        results["Entropy"][codec_name].append(entropy)
        results["Compressed Size"][codec_name].append(entropy_size)
        print((entropy, size, entropy_size))

print("SUMMARY:")
print(f"x: {x}")
print(f"y: {results}")
Пример #8
0
import argparse
import json
import os
from pathlib import Path
from datetime import datetime
from event_compression.codec import codecs
from event_compression.sequence import sequences

codecs = list(codecs().keys())
sequences = list(sequences().keys())


def get_parser(script_path):
	"""
	Instantiate a parser with arguments defined in standard location.

	**Arguments**:
		
		``script_path``: path to script for which to instantiate parser.

	**Return**:

		Standard parser for script under ``script_path``.

	**Example**:

		In your script file (in src/scripts)::

			import util

			parser = util.get_parser(__file__)