Exemple #1
0
def main():
    data = {"name": [], "image_size": [], "size_our": [], "size_jpg": [], "psnr_our": [], "psnr_jpg": []}

    codebook_size = 1024
    window_size = 4
    df = pd.read_csv(f"./experiments/compression_{codebook_size}_4.csv")

    for row in df.values:
        size_our = row[5]
        psnr_our = row[6]

        filename = f"./img/input/{row[1]}"
        out = f"./img/output/jpg/{row[1]}.jpg"

        cmd = f"magick convert {filename} -define jpeg:extent={int(size_our/8000)}kb {out}"
        print(cmd)
        subprocess.call(cmd, shell=True)

        size_jpg = os.path.getsize(out) * 8

        img = load_image(filename, path="")
        jpg_img = load_image(out, path="")
        psnr_jpg = PSNR(img, jpg_img)

        data["name"].append(row[1])
        data["size_our"].append(size_our)
        data["size_jpg"].append(size_jpg)
        data["psnr_our"].append(psnr_our)
        data["psnr_jpg"].append(psnr_jpg)
        data["image_size"].append(row[2])

    df = pd.DataFrame(data)
    print(df)
    df.to_csv(f"./experiments/jpg_compression_{codebook_size}_{window_size}.csv")
def main():
    from PIL import Image

    from vector_quantization.metrics import PSNR
    from vector_quantization.image import load_image, save_image
    from vector_quantization.codebooks import random_codebook
    from vector_quantization.vectorize import vectorize, image_from_vectors
    from vector_quantization.lbg import lbg
    from vector_quantization.mean_removal_quantization import mean_removal_quantize
    from vector_quantization.mean_removal_quantization import mean_removal_quantize_from_codebook
    from vector_quantization.differential_encoding import (
        median_adaptive_predictor_encoding,
        median_adaptive_predictor_decoding,
    )

    import matplotlib.pyplot as plt

    img = load_image("lennagrey.bmp")

    # Performing quantization with removed means (MRVQ)
    window_size = 4
    vectors = vectorize(img, window_size=window_size)
    means = np.mean(vectors, axis=1, keepdims=True)  # mean should be in shape like smaller image.
    height, width = img.shape
    means_reshaped = means.reshape((height // window_size, width // window_size))
    means_reshaped = means_reshaped.astype(int)

    # Differential encoding means from MRVQ
    encoded_means = median_adaptive_predictor_encoding(means_reshaped)
    encoded_means = encoded_means.astype(int)

    # Compress encoded means with Golomb Coder
    bit_code = golomb_compress(encoded_means)

    print("bit_code length", len(bit_code))
    print("without compression", encoded_means.size * 9)
    print("CR", len(bit_code) / (encoded_means.size * 9))

    # Decompress encoded means with Golomb Coder
    decoded_means = golomb_decompress(bit_code)

    # Differential decoding
    decoded_image = median_adaptive_predictor_decoding(decoded_means)

    plt.imshow(decoded_image)
    plt.show()
Exemple #3
0
def main():
    filenames = os.listdir("./img/input/")

    data = {
        "name": [],
        "size": [],
        "size_bmp": [],
        "size_quant": [],
        "size_golomb": [],
        "psnr": []
    }

    codebook_size = 2**9
    window_size = 4

    for filename in filenames:
        for i in range(0, 10):
            try:
                print(filename)
                img = load_image(filename, "./img/input/")

                bitcode = compression(img,
                                      codebook_size=codebook_size,
                                      window_size=window_size)
                size_bmp = img.size * 8
                size_golomb = len(bitcode)

                out_img = decompression(bitcode)
                psnr = PSNR(img, out_img)
            except ValueError:
                print(f"Try #{i} failed. Retrying..")
                continue

            data["name"].append(filename)
            data["size"].append(img.shape)
            data["size_bmp"].append(size_bmp)
            data["size_golomb"].append(size_golomb)
            data["size_quant"].append(
                np.sum(size_before_golomb_calc(img, codebook_size,
                                               window_size)))
            data["psnr"].append(psnr)
            break

    df = pd.DataFrame(data)
    print(df)
    df.to_csv(f"./experiments/compression_{codebook_size}_{window_size}.csv")
def mad():
    img = load_image("camera256.bmp")
    encoded = median_adaptive_predictor_encoding(img)
    # Debug values
    # There's something weird, as there are no negative numbers in encoded
    print(encoded)
    print(np.min(encoded))
    print(np.max(encoded))

    # Plot encoded image
    plt.imshow(encoded)
    plt.show()

    # Make histograms
    hist_img, bins_img = np.histogram(img, bins=np.arange(256))
    hist_img = hist_img / np.sum(hist_img)
    hist_encoded, bins_encoded = np.histogram(encoded.ravel(), bins=np.arange(-255, 256))
    hist_encoded = hist_encoded / np.sum(hist_encoded)

    # Plot histograms
    plt.plot(bins_img[:-1], hist_img, label="średnie")
    plt.plot(bins_encoded[:-1], hist_encoded, label="kodowanie różnicowe")
    plt.legend()
    plt.show()

    # Calculate entropy
    entropy_means = entropy(hist_img, base=2)
    entropy_encoded = entropy(hist_encoded, base=2)
    print(f"Entropia średnie = {entropy_means}, entropia kodowanie różnicowe = {entropy_encoded}")

    # Decode image
    decoded_image = median_adaptive_predictor_decoding(encoded)
    plt.imshow(decoded_image)
    plt.show()

    # PSNR
    print("PSNR: ", PSNR(img, decoded_image))
    f.close()


def from_file(file_path):
    f = open(file_path, "rb")
    bitcode = bitarray()
    bitcode.fromfile(f)
    f.close()

    img = decompression(bitcode)
    return img


if __name__ == "__main__":
    # with file
    img = load_image("balloon.bmp")
    file_path = "./img/output/balloon.vc"
    to_file(img, file_path)
    out_img = from_file(file_path)

    print("PSNR:", PSNR(img, out_img))
    Image.fromarray(out_img).show()

    # without file
    img = load_image("balloon.bmp")
    bitcode = compression(img)
    out_img = decompression(bitcode)

    print("PSNR:", PSNR(img, out_img))
    print("bit_code length", len(bitcode))
    print("without compression", img.size * 8)