#!/usr/bin/env python
# coding: utf-8

# In[23]:


import matplotlib.pyplot as plt
import numpy as np
import time

from PIL import Image


# In[28]:


import numpy as np
from PIL import Image
 
# FUNCTION DEFINTIONS:
 
# تجزیه ابعاد ماتریس
def openImage(imagePath):
    imOrig = Image.open(imagePath)
    im = np.array(imOrig)
 
    aRed = im[:, :, 0]
    aGreen = im[:, :, 1]
    aBlue = im[:, :, 2]
 
    return [aRed, aGreen, aBlue, imOrig]
 
# فشرده سازی کانال ها
def compressSingleChannel(channelDataMatrix, singularValuesLimit):
    uChannel, sChannel, vhChannel = np.linalg.svd(channelDataMatrix)
    aChannelCompressed = np.zeros((channelDataMatrix.shape[0], channelDataMatrix.shape[1]))
    k = singularValuesLimit
 
    leftSide = np.matmul(uChannel[:, 0:k], np.diag(sChannel)[0:k, 0:k])
    aChannelCompressedInner = np.matmul(leftSide, vhChannel[0:k, :])
    aChannelCompressed = aChannelCompressedInner.astype('uint8')
    return aChannelCompressed
 
 
# MAIN PROGRAM:
print ('*** Image Compression using SVD - a demo')
aRed, aGreen, aBlue, originalImage = openImage('image.jpg')
 
# image width and height:
imageWidth = 512
imageHeight = 512
 
#number of singular values to use for reconstructing the compressed image
singularValuesLimit = int(input("Singular Value Limit : "))
 
aRedCompressed = compressSingleChannel(aRed, singularValuesLimit)
aGreenCompressed = compressSingleChannel(aGreen, singularValuesLimit)
aBlueCompressed = compressSingleChannel(aBlue, singularValuesLimit)
 
imr=Image.fromarray(aRedCompressed,mode=None)
img=Image.fromarray(aGreenCompressed,mode=None)
imb=Image.fromarray(aBlueCompressed,mode=None)
 
newImage = Image.merge("RGB", (imr,img,imb))
 
plt.figure(figsize=(9,6))
plt.imshow(originalImage)
plt.figure(figsize=(9,6))
plt.imshow(newImage)
# originalImage.show()
# newImage.show()
 
# CALCULATE AND DISPLAY THE COMPRESSION RATIO
mr = imageHeight
mc = imageWidth
 
originalSize = mr * mc * 3
compressedSize = singularValuesLimit * (1 + mr + mc) * 3
 
print('original size:')
print(originalSize)
 
print('compressed size:')
print(compressedSize)
 
print('Ratio compressed size / original size:')
ratio = compressedSize * 1.0 / originalSize
print(ratio)
 
print('Compressed image size is ' + str( round(ratio * 100 ,2)) + '% of the original image ' )
print('DONE - Compressed the image! Over and out!')


# In[ ]:




