svd_mpsic/svd_operations.py

95 lines
2.9 KiB
Python
Raw Normal View History

import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.color import rgb2gray
from skimage import img_as_ubyte, img_as_float
from ipywidgets import interact, interactive, interact_manual
from numpy.linalg import svd
import ipywidgets as widgets
gray_images = {
"cat": rgb2gray(img_as_float(data.chelsea())),
"astro": rgb2gray(img_as_float(data.astronaut())),
"camera": data.camera(),
"coin": data.coins(),
"clock": data.clock(),
"blobs": data.binary_blobs(),
"coffee": rgb2gray(img_as_float(data.coffee()))
}
def mc_pi(ntrials):
"""
calculate the value of pi using montecarlo method and visualize the process
"""
x = np.random.random(ntrials)
y = np.random.random(ntrials)
# masking
inside_circle = x ** 2 + y ** 2 < 1
unit_circle_x = np.linspace(0, 1, 100)
unit_circle = [unit_circle_x, np.sqrt(1.0 - unit_circle_x ** 2)]
plt.plot(*unit_circle, color='black')
plt.scatter(x[inside_circle], y[inside_circle], marker='.', color='blue', s=1)
plt.scatter(x[~inside_circle], y[~inside_circle], marker='.', color='red', s=1)
plt.title("value of $\pi$=" + str(4.0 * np.sum(inside_circle) / float(ntrials)))
def compress_svd(image, k):
"""
Perform svd decomposition and truncated (using k singular values/vectors) reconstruction
returns
--------
reconstructed matrix reconst_matrix, array of singular values s
"""
U, s, V = svd(image, full_matrices=False)
reconst_matrix = np.dot(U[:, :k], np.dot(np.diag(s[:k]), V[:k, :]))
return reconst_matrix, s
def compress_show_gray_images(img_name, k):
"""
compresses gray scale images and display the reconstructed image.
Also displays a plot of singular values
"""
image = gray_images[img_name]
original_shape = image.shape
reconst_img, s = compress_svd(image, k)
fig, axes = plt.subplots(1, 2, figsize=(8, 5))
axes[0].plot(s)
compression_ratio = 100.0 * (k * (original_shape[0] + original_shape[1]) + k) / (
original_shape[0] * original_shape[1])
axes[1].set_title("compression ratio={:.2f}".format(compression_ratio) + "%")
axes[1].imshow(reconst_img, cmap='gray')
axes[1].axis('off')
fig.tight_layout()
def compute_k_max(img_name):
"""
utility function for calculating max value of the slider range
"""
img = gray_images[img_name]
m, n = img.shape
return m * n / (m + n + 1)
# set up the widgets
list_widget = widgets.Dropdown(options=list(gray_images.keys()))
int_slider_widget = widgets.IntSlider(min=1, max=compute_k_max('cat'))
def update_k_max(*args):
img_name = list_widget.value
int_slider_widget.max = compute_k_max(img_name)
list_widget.observe(update_k_max, 'value')
interact(compress_show_gray_images, img_name=list_widget, k=int_slider_widget)
mc_widget = interactive(mc_pi, ntrials=(1, 100000, 10))
mc_widget