Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import pandas as pd
- from sklearn.decomposition import TruncatedSVD
- import matplotlib.pyplot as plt
- import matplotlib.image as mpimg
- class ImageCompressor:
- def __init__(self, n_components):
- self.n_components = n_components
- self.svd = TruncatedSVD(n_components=self.n_components)
- def fit_transform(self, img):
- img_red = img[:, :, 0]
- img_green = img[:, :, 1]
- img_blue = img[:, :, 2]
- components_red = self.svd.fit_transform(img_red)
- compressed_red = np.dot(components_red, self.svd.components_)
- components_green = self.svd.fit_transform(img_green)
- compressed_green = np.dot(components_green, self.svd.components_)
- components_blue = self.svd.fit_transform(img_blue)
- compressed_blue = np.dot(components_blue, self.svd.components_)
- compressed_red = compressed_red.astype(int)
- compressed_blue = compressed_blue.astype(int)
- compressed_green = compressed_green.astype(int)
- compressed_array = np.stack((compressed_red, compressed_green, compressed_blue), axis=2)
- compressed_array = np.clip(compressed_array, 0, 255)
- return compressed_array
- img = mpimg.imread('IMG_2844.jpg')
- df = img[:, :, 0]
- img0 = plt.imshow(df, cmap='grey')
- plt.title('Оригінальне зображення')
- plt.show()
- svd = TruncatedSVD(n_components=df.shape[1])
- svd.fit(df)
- eigenvalues = svd.singular_values_
- plt.bar(range(1, 21), eigenvalues[:20])
- plt.xlabel('Номер власного значення')
- plt.ylabel('Власне значення')
- plt.title('Гістограма перших 20 власних значень')
- plt.show()
- explained_variance_ratio = svd.explained_variance_ratio_
- cumulative_explained_variance = np.cumsum(explained_variance_ratio)
- plt.plot(range(1, len(cumulative_explained_variance) + 1), 100 - cumulative_explained_variance * 100, marker='o')
- plt.xlabel('Кількість використаних компонент')
- plt.ylabel('Втрата інформації, %')
- plt.show()
- n_components_to_plot = [1, 3, 5, 10, 15, 20]
- fig, axs = plt.subplots(2, 3, figsize=(15, 10))
- axs = axs.ravel()
- for i, n in enumerate(n_components_to_plot):
- svd = TruncatedSVD(n_components=n)
- components = svd.fit_transform(df)
- reconstructed_df = pd.DataFrame(np.dot(components, svd.components_))
- axs[i].imshow(reconstructed_df, cmap="gray")
- axs[i].set_title(f'Кількість компонент = {n}')
- plt.show()
- plt.title('Оригінальне зображення')
- plt.imshow(img)
- plt.show()
- n_components_to_plot = [1, 3, 5, 10, 15, 20]
- fig, axs = plt.subplots(2, 3, figsize=(15, 10))
- axs = axs.ravel()
- for i, n in enumerate(n_components_to_plot):
- compressor = ImageCompressor(n_components=n)
- reconstructed_img = compressor.fit_transform(img)
- axs[i].imshow(reconstructed_img)
- axs[i].set_title(f'Кількість компонент = {n}')
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement