import numpy as np
from matplotlib import image
from matplotlib import pyplot as plt


img_path = r'C:\Users\asus\Pictures\123.jpg'  
img = image.imread(img_path)


if len(img.shape) == 3:
    r = img[:, :, 0]
    g = img[:, :, 1]
    b = img[:, :, 2]
else:
    img = np.expand_dims(img, axis=2)
    r = img[:, :, 0]
    g = img[:, :, 0]
    b = img[:, :, 0]


k = 100


def compress_channel(channel):
    U, s, Vt = np.linalg.svd(channel)
    s_k = np.diag(s[:k])  
    compressed_channel = U[:, :k] @ s_k @ Vt[:k, :]
    return compressed_channel


r_compressed = compress_channel(r)
g_compressed = compress_channel(g)
b_compressed = compress_channel(b)


compressed_img = np.stack([r_compressed, g_compressed, b_compressed], axis=2)
compressed_img = np.clip(compressed_img, 0, 255).astype(np.uint8)


plt.imshow(compressed_img)
plt.axis('off')
plt.savefig('compressed_image.jpg')  
plt.show()