{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "pycharm": { "is_executing": true, "name": "#%%\n" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/var/folders/tq/jq5nwbnj7v10tls99x99qbh40000gn/T/ipykernel_65173/3026179557.py:15: DeprecationWarning: Importing display from IPython.core.display is deprecated since IPython 7.14, please import from IPython display\n", " from IPython.core.display import display, HTML\n" ] }, { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from skimage import data\n", "from skimage.color import rgb2gray\n", "from skimage import img_as_ubyte,img_as_float\n", "from numpy.linalg import svd\n", "import scipy.linalg as la\n", "from PIL import Image\n", "from ipywidgets import interact\n", "from numpy.linalg import eig\n", "from math import isclose\n", "import pprint\n", "\n", "# zmień szerokość komórki\n", "from IPython.core.display import display, HTML\n", "display(HTML(\"\"))\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "#Ta linia jest wymagana do wyświetlania wizualizacji w przeglądarce\n", "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "# Kompresja obrazów z wykorzystaniem rozkładu SVD" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "Metodę SVD zastosujemy do kompresji obrazów. SVD dokonuje dekompozycji macierzy prostokątnej $M$ na trzy części.\n", "$M=U\\Sigma V^T$ -\n", "- $U$ - macierz, w której kolumny są wektorami własnymi macierzy $MM^T$ (lewe wektory osobliwe - 'left singular vectors'). Wektory te tworzą układ ortonormalny.\n", "- $\\Sigma$ - macierz diagonalna, która na swojej diagonalii ma nieujemne wartości osobliwe (szczególne), czyli pierwiastki wartości własnych macierzy $M^TM$ uporządkowane nierosnąco\n", "- $V$ - macierz, w której kolumny są wektorami własnymi macierzy $M^TM$ (prawe wektory osobliwe - 'right singular vectors'). Wektory te tworzą układ ortonormalny.\n", "\n", "SVD polega na rekonstrukcji oryginalnej macierzy jako kombinacji liniowej kilku macierzy rangi jeden. Macierz rangi jeden można wyrazić jako iloczyn zewnętrzny dwóch wektorów kolumnowych. \n", "\n", "$M=\\sigma_1u_1v_1^T+\\sigma_2u_2v_2^T+\\sigma_3u_3v_3^T+\\sigma_4u_4v_4^T+....$ .\n", "\n", "$rank M=r$ .\n", "$M=\\sum_{i=1}^{r} \\sigma_iu_iv_i^T$\n", "\n", "Macierz o randze r będzie miała r takich wyrazów.\n", "\n", "Tutaj $\\sigma_1,\\sigma_2,\\sigma_3 ...$ są wartościami osobliwymi. $u_1,u_2,u_3 ...$ i $v_1,v_2,v_3 ...$ są kolejnymi kolumnami (wektorami własnymi) z macierzy U i V.\n", "\n", "Kompresja obrazu przy użyciu SVD polega na wykorzystaniu faktu, że tylko nieliczne wartości osobliwe są duże. Chociaż obrazy ze świata rzeczywistego mają pełną rangę, to ich efektywna ranga jest niska, co oznacza, że tylko kilka wartości osobliwych rozkładu SVD obrazów będzie dużych." ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "### skimage - biblioteka do przetwarzania obrazów\n", "\n", "Do pracy z obrazami w Pythonie używamy biblioteki do przetwarzania obrazów ```skimage``` (z rodziny pakietów ```sci-kit```). Ma ona moduł o nazwie data, który udostępnia zestaw obrazów. Wczytujemy kilka obrazów i konwertujemy je do formatu skali szarości. Obrazy te są przechowywane w słowniku ```gray_images```." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "gray_images = {\n", " \"cat\":rgb2gray(img_as_float(data.chelsea())),\n", " \"astro\":rgb2gray(img_as_float(data.astronaut())),\n", " \"line\": rgb2gray(img_as_float(Image.open('line.jpeg'))),\n", " \"camera\":data.camera(),\n", " \"coin\": data.coins(),\n", " \"clock\":data.clock(),\n", " \"text\":data.text(),\n", " \"page\":data.page(),\n", " \"blobs\":data.binary_blobs(),\n", " \"coffee\":rgb2gray(img_as_float(data.coffee()))\n", "}" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "### SVD w python'ie\n", "Używamy funkcji ```svd``` z biblioteki ```numpy.linalg``` do obliczenia rozkładu SVD naszej macierzy. Funkcja svd zwraca U,s,V .\n", " - U macierz, w której kolumny są wektorami własnymi macierzy $MM^T$\n", " - s jest tablicą numpy rangi 1 z wartościami osobliwymi\n", " - V macierz, w której wiersze są wektorami własnymi macierzy $M^TM$ - odpowiednik $V^T$ w tradycyjnej literaturze algebry liniowej\n", " \n", "Zrekonstruowana aproksymacja oryginalnej macierzy jest wykonywana przy użyciu podzbioru wektorów osobliwych, jak poniżej w funkcji ``compress_svd``. Używamy ```NumPy Array Slicing```, aby wybrać k wektorów osobliwych i wartości osobliwych. Zamiast przechowywać $m\\times n$ wartości dla oryginalnego obrazu, możemy teraz przechowywać $k(m+n)+k$ wartości\n", "\n", " reconst_matrix = np.dot(U[:,:k],np.dot(np.diag(s[:k]),V[:k,:]))\n", " " ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "U: [[ 0. 0. 1. 0.]\n", " [ 0. 1. 0. 0.]\n", " [ 0. 0. 0. -1.]\n", " [ 1. 0. 0. 0.]] \n", " s: [4. 3. 2.23606798 0. ] \n", " V: [[ 0. 1. 0. 0. 0. ]\n", " [ 0. 0. 1. 0. 0. ]\n", " [ 0.4472136 0. 0. 0. 0.89442719]\n", " [ 0. 0. 0. 1. 0. ]\n", " [-0.89442719 0. 0. 0. 0.4472136 ]] \n", "\n", "--------------------------------------\n", "U1: [[ 0. 0. 1. 0.]\n", " [ 0. 1. 0. 0.]\n", " [ 0. 0. 0. -1.]\n", " [ 1. 0. 0. 0.]] \n", " s1: [4. 3. 2.23606798 0. ] \n", " V1: [[-0. 1. 0. 0. 0. ]\n", " [-0. 0. 1. 0. 0. ]\n", " [ 0.4472136 0. 0. 0. 0.89442719]\n", " [ 0. 0. 0. 1. 0. ]\n", " [-0.89442719 0. 0. 0. 0.4472136 ]] \n", "\n", "reconst -------------- [[1. 0. 0. 0. 2.]\n", " [0. 0. 3. 0. 0.]\n", " [0. 0. 0. 0. 0.]\n", " [0. 4. 0. 0. 0.]]\n" ] } ], "source": [ "def calculate(A):\n", " n = A.shape[0]\n", " m = A.shape[1]\n", " S = np.zeros(n)\n", "\n", " helper = np.matmul(A, np.transpose(A))\n", " eigenvalues, eigenvectors = eig(helper)\n", " \n", " index = eigenvalues.argsort()[::-1]\n", " eigenvalues = np.real(eigenvalues)\n", " eigenvectors = np.real(eigenvectors)\n", " eigenvalues = eigenvalues[index]\n", " eigenvectors = eigenvectors[:, index]\n", " U = eigenvectors\n", "\n", " helper2 = np.matmul(np.transpose(A), A)\n", " eigenvalues2, eigenvectors2 = eig(helper2)\n", " index2 = eigenvalues2.argsort()[::-1]\n", " eigenvalues2 = np.real(eigenvalues2)\n", " eigenvectors2 = np.real(eigenvectors2)\n", " eigenvalues2 = eigenvalues2[index2]\n", " eigenvectors2 = eigenvectors2[:, index2]\n", " V = np.transpose(eigenvectors2)\n", " \n", " j = 0\n", " for i in eigenvalues2:\n", " if j == S.size:\n", " break\n", " elif i >= 0:\n", " S[j] = np.sqrt(i)\n", " j += 1\n", "\n", " S[::-1].sort()\n", "\n", " return U, S, V\n", "\n", "def check_sign_V(V, builtin):\n", " if builtin.shape[0] < builtin.shape[1]:\n", " for i in range(0,builtin.shape[0]):\n", " for j in range(0,builtin.shape[1]):\n", " if builtin[j][i] < 0.0 and V[j][i] > 0.0:\n", " V[j][i] *= -1\n", " elif builtin[j][i] > 0.0 and V[j][i] < 0.0:\n", " V[j][i] *= -1\n", " else:\n", " for i in range(0,builtin.shape[0]):\n", " for j in range(0,builtin.shape[1]):\n", " if builtin[i][j] < 0.0 and V[i][j] > 0.0:\n", " V[i][j] *= -1\n", " elif builtin[i][j] > 0.0 and V[i][j] < 0.0:\n", " V[i][j] *= -1\n", "\n", " return V\n", "\n", "\n", "def check_sign_U(U, builtin):\n", " if builtin.shape[0] < builtin.shape[1]: \n", " for i in range(0,builtin.shape[0]):\n", " for j in range(0,builtin.shape[1]):\n", " if builtin[j][i] < 0.0 and U[j][i] > 0.0:\n", " U[j][i] *= -1\n", " elif builtin[j][i] > 0.0 and U[j][i] < 0.0:\n", " U[j][i] *= -1\n", " else:\n", " for i in range(0,builtin.shape[0]):\n", " for j in range(0,builtin.shape[1]):\n", " if builtin[i][j] < 0.0 and U[i][j] > 0.0:\n", " U[i][j] *= -1\n", " elif builtin[j][j] > 0.0 and U[i][j] < 0.0:\n", " U[i][j] *= -1\n", "\n", " return U\n", "\n", "\n", "a = np.array([[1,0, 0, 0, 2], \n", " [0, 0, 3, 0, 0],\n", " [0, 0, 0, 0, 0],\n", " [0, 4, 0, 0, 0]])\n", "U,s,V = calculate(a)\n", "U1,s1,V1 = svd(a)\n", "U = check_sign_U(U, U1)\n", "V = check_sign_V(V, V1)\n", "print(V.shape[0])\n", "print('U: ', U, '\\n', 's: ',s, '\\n','V: ',V, '\\n')\n", "print('--------------------------------------')\n", "print('U1: ',U1, '\\n','s1: ',s1, '\\n', 'V1: ',V1, '\\n')\n", "k = 4\n", "reconst_matrix4 = np.dot(U[:,:k],np.dot(np.diag(s[:k]),V[:k,:]))\n", "print('reconst -------------- ', reconst_matrix4)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "def compress_svd(image,k):\n", " \"\"\"\n", " Wykonaj dekompozycję SVD, a następnie okrojoną rekonstrukcję (przy użyciu k wartości/wektorów osobliwych)\n", " \"\"\"\n", " image = np.real(image)\n", " U,s,V = svd(image,full_matrices=False)\n", " reconst_matrix = np.dot(U[:,:k],np.dot(np.diag(s[:k]),V[:k,:]))\n", "\n", " return reconst_matrix,s" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "### Kompresja obrazów w skali szarości\n", "Poniższa funkcja ``compress_show_gray_images`` przyjmuje nazwę obrazu (img_name) i liczbę wartości/wektorów osobliwych (k), które mają być użyte w skompresowanej rekonstrukcji. Na wykresie są wartości osobliwe oraz obraz." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "def compress_show_gray_images(img_name,k):\n", " \"\"\"\n", " Kompresuje obrazy w skali szarości i wyświetla zrekonstruowany obraz.\n", " Wyświetla również wykres wartości singularnych\n", " \"\"\"\n", " image=gray_images[img_name]\n", " original_shape = image.shape\n", " reconst_img,s = compress_svd(image,k)\n", " fig,axes = plt.subplots(1,2,figsize=(8,5))\n", " axes[0].plot(s)\n", " compression_ratio =100.0* (k*(original_shape[0] + original_shape[1])+k)/(original_shape[0]*original_shape[1])\n", " axes[1].set_title(\"compression ratio={:.2f}\".format(100 - compression_ratio)+\"%\")\n", " axes[1].imshow(reconst_img,cmap='gray')\n", " axes[1].axis('off')\n", " fig.tight_layout()\n", " # compression rate = 100% * (k * (height + width + k)) / (height + width)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "W celu zbadania, jak jakość zrekonstruowanego obrazu zmienia się wraz z $k$ należy użyć poniższego interaktywnego widżetu." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "def compute_k_max(img_name):\n", " \"\"\"\n", " Funkcja do obliczania maksymalnej wartości zakresu suwaka \"k\"\n", " \"\"\"\n", " img = gray_images[img_name]\n", " m,n = img.shape\n", " return m*n/(m+n+1)\n", "\n", "import ipywidgets as widgets\n", "\n", "list_widget = widgets.Dropdown(options=list(gray_images.keys()))\n", "int_slider_widget = widgets.IntSlider(min=1,max=compute_k_max('cat'))\n", "\n", "def update_k_max(*args):\n", " img_name=list_widget.value\n", " int_slider_widget.max = compute_k_max(img_name)\n", "\n", "list_widget.observe(update_k_max,'value')" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "def print_matrices(img_name, k):\n", " \"\"\"\n", " Wyświetlanie macierzy U V S wraz z wymiarami.\n", " \"\"\"\n", "\n", " if img_name not in gray_images.keys():\n", " return\n", " \n", " image=gray_images[img_name]\n", " original_shape = image.shape\n", " print(f\"Input image dimensions. Width:{original_shape[1]} Height:{original_shape[0]}\")\n", "\n", " U,s,V = svd(image,full_matrices=False)\n", " print(f\"Shape of U matrix: {U[:,:k].shape}\")\n", " print(f\"U MATRIX: {U[:,:k]}\")\n", " print('*' * 100)\n", " print(f\"Shape of S matrix: {s[:k].shape}\")\n", " print(f\"S MATRIX: {np.diag(s[:k])}\")\n", " print('*' * 100)\n", " print(f\"Shape of V matrix: {V[:k,:].shape}\")\n", " print(f\"V MATRIX: {V[:k,:]}\")\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "702fd8dcaa0c495d8944c5b0dd82892b", "version_major": 2, "version_minor": 0 }, "text/plain": [ "interactive(children=(Dropdown(description='img_name', options=('cat', 'astro', 'line', 'camera', 'coin', 'clo…" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "interact(print_matrices, img_name=list_widget, k=int_slider_widget)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "pycharm": { "name": "#%%\n" }, "scrolled": false }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "405c92f2998843498e9cd20675ba2b4e", "version_major": 2, "version_minor": 0 }, "text/plain": [ "interactive(children=(Dropdown(description='img_name', options=('cat', 'astro', 'line', 'camera', 'coin', 'clo…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "interact(compress_show_gray_images,img_name=list_widget,k=int_slider_widget);" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "### Ładowanie kolorowych obrazów" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "color_images = {\n", " \"cat\":img_as_float(data.chelsea()),\n", " \"astro\":img_as_float(data.astronaut()),\n", " \"coffee\":img_as_float(data.coffee()),\n", " \"rocket\":img_as_float(data.rocket()),\n", " \"koala\": img_as_float(Image.open('koala.jpeg')),\n", " \"orange\": img_as_float(Image.open('orange.jpeg')),\n", " \"teacher\": img_as_float(Image.open('teacher.jpeg'))\n", "}\n" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "### Kompresja kolorowych obrazów\n", "\n", "Obrazy kolorowe są reprezentowane w Pythonie jako trójwymiarowe tablice numpy - trzeci wymiar reprezentuje wartości kolorów (czerwony, zielony, niebieski). Jednak metoda svd ma zastosowanie do macierzy dwuwymiarowych. W tym celu musimy przekonwertować tablicę trójwymiarową na tablicę dwuwymiarową, zastosować svd i zrekonstruować ją z powrotem jako tablicę trójwymiarową. Istnieją dwa sposoby, aby to zrobić: \n", " - Metoda reshape\n", " - Metoda layers (warstwowa)\n", "\n", "Obie te metody pokażemy poniżej.\n" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "#### Metoda reshape do kompresji kolorowych obrazów\n", " \n", "Metoda ta polega na spłaszczeniu trzeciego wymiaru tablicy obrazów do drugiego wymiaru przy użyciu metody ```reshape``` z biblioteki ```numpy```.\n", " \n", " ``` image_reshaped = image.reshape((original_shape[0],original_shape[1]*3))```\n", "\n", "Dekompozycja svd jest stosowana do wynikowej, przekształconej tablicy i rekonstruowana z żądaną liczbą wartości/wektorów osobliwych. Tablica obrazów jest przekształcana z powrotem do trzech wymiarów przez kolejne wywołanie metody reshape.\n", " \n", " ```image_reconst = image_reconst.reshape(original_shape)```" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "def compress_show_color_images_reshape(img_name,k):\n", " \"\"\"\n", " Kompresowanie i wyświetlanie zrekonstruowanego obrazu kolorowego przy użyciu metody reshape.\n", " \"\"\"\n", " image = color_images[img_name]\n", " original_shape = image.shape\n", " image_reshaped = image.reshape((original_shape[0],original_shape[1]*3))\n", " image_reconst,_ = compress_svd(image_reshaped,k)\n", " image_reconst = image_reconst.reshape(original_shape)\n", " compression_ratio =100.0* (k*(original_shape[0] + 3*original_shape[1])+k)/(original_shape[0]*original_shape[1]*original_shape[2])\n", " plt.title(\"compression ratio={:.2f}\".format(100 - compression_ratio)+\"%\")\n", " plt.imshow(image_reconst)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "Oto interaktywny widżet do badania kompresji obrazów kolorowych metodą reshape. Przeciągając suwak w celu zmiany wartości $k$, można zaobserwować, jak zmienia się jakość obrazu. Można także badać różne obrazy, wybierając je za pomocą rozwijanego widżetu." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "def compute_k_max_color_images(img_name):\n", " image = color_images[img_name]\n", " original_shape = image.shape\n", " return (original_shape[0]*original_shape[1]*original_shape[2])//(original_shape[0] + 3*original_shape[1] + 1)\n", "\n", "\n", "list_widget = widgets.Dropdown(options=list(color_images.keys()))\n", "int_slider_widget = widgets.IntSlider(min=1,max=compute_k_max_color_images('cat'))\n", "def update_k_max_color(*args):\n", " img_name=list_widget.value\n", " int_slider_widget.max = compute_k_max_color_images(img_name)\n", "list_widget.observe(update_k_max_color,'value')" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "def print_color_matrices(img_name,k):\n", " \"\"\"\n", " Wyświetlanie macierzy U V S wraz z wymiarami.\n", " \"\"\"\n", " image = color_images[img_name]\n", " original_shape = image.shape\n", " image_reconst_layers = [compress_svd(image[:,:,i],k)[0] for i in range(3)]\n", " print(image_reconst_layers)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "6d2c561f500d42be903e30933d3fe7d6", "version_major": 2, "version_minor": 0 }, "text/plain": [ "interactive(children=(Dropdown(description='img_name', options=('cat', 'astro', 'coffee', 'rocket', 'koala', '…" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "interact(print_color_matrices, img_name=list_widget, k=int_slider_widget)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "f4b99140de5d495580f6abaa20a04b4c", "version_major": 2, "version_minor": 0 }, "text/plain": [ "interactive(children=(Dropdown(description='img_name', options=('cat', 'astro', 'coffee', 'rocket', 'koala', '…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "interact(compress_show_color_images_reshape,img_name=list_widget,k=int_slider_widget);" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "### Metoda layers (warstwowa) do kompresji kolorowych obrazów\n", "W funkcji ``compress_show_color_images_layer``, traktujemy kolorowy obraz jako stos 3 oddzielnych dwuwymiarowych obrazów (warstwy czerwona, niebieska i zielona). Stosujemy okrojoną rekonstrukcję svd na każdej dwuwymiarowej warstwie osobno.\n", "\n", "``image_reconst_layers = [compress_svd(image[:,:,i],k)[0] for i in range(3)]``.\n", "\n", "I ponownie łączymy zrekonstruowane warstwy razem.\n", "\n", "```\n", "image_reconst = np.zeros(image.shape)\n", "for i in range(3):\n", " image_reconst[:,:,,i] = image_reconst_layers[i]\n", "``` " ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "def compress_show_color_images_layer(img_name,k):\n", " \"\"\"\n", " Kompresowanie i wyświetlanie zrekonstruowanego obrazu kolorowego przy użyciu metody warstwowej.\n", " \"\"\"\n", " image = color_images[img_name]\n", " original_shape = image.shape\n", " image_reconst_layers = [compress_svd(image[:,:,i],k)[0] for i in range(3)]\n", "# print(image_reconst_layers)\n", " image_reconst = np.zeros(image.shape)\n", " for i in range(3):\n", " image_reconst[:,:,i] = image_reconst_layers[i]\n", " \n", " compression_ratio =100.0*3* (k*(original_shape[0] + original_shape[1])+k)/(original_shape[0]*original_shape[1]*original_shape[2])\n", " plt.title(\"compression ratio={:.2f}\".format(100- compression_ratio)+\"%\")\n", " plt.imshow(image_reconst, vmin=0, vmax=255)\n" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "Oto widżet do badania metody layers (warstwowej) kompresji obrazów kolorowych." ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "def compute_k_max_color_images_layers(img_name):\n", " image = color_images[img_name]\n", " original_shape = image.shape\n", " return (original_shape[0]*original_shape[1]*original_shape[2])// (3*(original_shape[0] + original_shape[1] + 1))\n", "\n", "\n", "list_widget = widgets.Dropdown(options=list(color_images.keys()))\n", "int_slider_widget = widgets.IntSlider(min=1,max=compute_k_max_color_images_layers('cat'))\n", "def update_k_max_color_layers(*args):\n", " img_name=list_widget.value\n", " int_slider_widget.max = compute_k_max_color_images_layers(img_name)\n", "list_widget.observe(update_k_max_color_layers,'value')" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "6363d12d2fbe49518bf5735f6472a497", "version_major": 2, "version_minor": 0 }, "text/plain": [ "interactive(children=(Dropdown(description='img_name', options=('cat', 'astro', 'coffee', 'rocket', 'koala', '…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "interact(print_color_matrices,img_name=list_widget,k=int_slider_widget);" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "edd32a03e6184b15ae3283c8e24f2d3e", "version_major": 2, "version_minor": 0 }, "text/plain": [ "interactive(children=(Dropdown(description='img_name', options=('cat', 'astro', 'coffee', 'rocket', 'koala', '…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "interact(compress_show_color_images_layer,img_name=list_widget,k=int_slider_widget);" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.13" } }, "nbformat": 4, "nbformat_minor": 1 }