#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan  9 22:07:38 2018

@author: christianehelzel
"""

# Ziel: Erstelle einen Film, der die rekonstruierten Bilder 
# in Abhängigkeit von k zeigt
#
# Diese Routine erzeugt jpg - Files die in einem Verzeichnis
# ./animation abgespeichert werden
#
# Nach Aufruf dieser Routine geht man in das Verzeichnis 
# ./animation und ruft den folgenden Befehl auf:
#
# unter Linux:
# convert -delay 20 -loop 0 *.png movie.gif
#  

import numpy as np
import numpy.linalg as npl
from matplotlib import pyplot as plt

#Bild laden
image_color = plt.imread('globe.png')

[m,n,l] = image_color.shape

r_layer = image_color[:,:,0]
g_layer = image_color[:,:,1]
b_layer = image_color[:,:,2]

#Singulärwertzerlegung
U_r, sigma_r, Vh_r = npl.svd(r_layer);
U_g, sigma_g, Vh_g = npl.svd(g_layer);
U_b, sigma_b, Vh_b = npl.svd(b_layer);

U_rgb = [U_r,U_g,U_b]
Vh_rgb = [Vh_r,Vh_g,Vh_b]
sigma_rgb = [sigma_r,sigma_g,sigma_b]

image_compressed = np.empty((m,n,3))

# Bilder rekonstruieren (verschiedene Anzahl an verwendeten Singulärwerten) 
# und als PNG-Bild speichern
for x in range(1,15):
    k = x**2
    
    for i in range(3):
    
        U = U_rgb[i]
        Vh = Vh_rgb[i]
        sigma = sigma_rgb[i]
        
        sigma_k = sigma[:k];
        U_k = U[:, :k];
        Vh_k = Vh[:k, :];
        image_compressed[:,:,i] = U_k @ np.diag(sigma_k) @ Vh_k; 
        image_compressed=np.clip(image_compressed,0,1)
        
    plt.imsave('animation/outfile{0:2d}.png'.format(x), image_compressed) 
    # plt.imsave() : Save an array as an image file

