Demo entry 6659656

Python svd code to try.

   

Submitted by Adarsh on Nov 12, 2017 at 03:58
Language: Python 3. Code size: 1.1 kB.

# Import the necessary packages
# use sudo pip3 install scikit-image for skimage

import numpy as np
from scipy import linalg
from skimage import data
import matplotlib.pyplot as plt

# Get an image from `skimage`
img= data.camera()

# Check number of singular values
singular_values = linalg.svdvals(img)
print('Number of singlular values : ', singular_values.shape)

# Singular Value Decomposition.
# https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.linalg.svd.html
U, s, Vh = linalg.svd(img, full_matrices=1)

# Number of singluar values to use, i.e dimensions.
# Change this number and see how clarity of image varies
n = 32 
A = np.dot(U[:,0:n], 
          np.dot(np.diag(s[0:n]), Vh[0:n,:]))

fig = plt.figure(figsize=(8, 3))

# Add a subplot to the figure
ax = fig.add_subplot(121)

# Plot `img` on grayscale
ax.imshow(img)

# Add a second subplot to the figure
ax2 = fig.add_subplot(122)

# Plot `A` in the second subplot
ax2.imshow(A)

# Add a title
fig.suptitle('Image Compression with SVD', fontsize=14, fontweight='bold')

# Show the plot
plt.show()

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).