SVD图像处理(MATLAB)

news2024/10/13 2:18:38

使用SVD处理图像模拟演示

参考文献

https://github.com/matzewolf/Image_compression_SVD/blob/master/svd_compress.m

在这里插入图片描述

MATLAB代码

clc;
clearvars;
close all;


A_org=imread("lena256.bmp");
compr=20;
A_org=double(A_org);
 A_red  = svd_compress( A_org, compr );
subplot(1,2,1),imshow(A_org,[]);
subplot(1,2,2),imshow(A_red,[]);


function [ A_red ] = svd_compress( A_org, compr )

% svd_compress compresses an input matrix (e.g. an image) using the
% Singular Value Decomposition (SVD).
%   Input args: A_org: Any matrix with double real entries, e.g. an image 
%   file (converted from uint8 to double).
%   compr: Quality of compression. If 0 <= compr < 1, it only keeps
%   Singular Values (SVs) larger than compr times the biggest SV. If 1 <= 
%   compr <= number of SVs, it keeps the biggest compr SVs. Otherwise the 
%   function returns an error.
%   Output args: A_red: Compressed version of A_org in double using the
%   SVD, e.g. an image file (convert from double to uint8).

% SVD on the original matrix
[U,S,V] = svd(A_org);

% Extract Singular Values (SVs)
singvals = diag(S);

% Determine SVs to be saved
if compr >= 0 && compr < 1
    % only SVs bigger than compr times biggest SV
    indices = find(singvals >= compr * singvals(1));
elseif compr >= 1 && compr <= length(singvals)
    % only the biggest compr SVs
    indices = 1:compr;
else
    % return error
    error('Incorrect input arg: compr must satisfy 0 <= compr <= number of Singular Values');
end

% Truncate U,S,V
U_red = U(:,indices);
S_red = S(indices,indices);
V_red = V(:,indices);

% Calculate compressed matrix
A_red = U_red * S_red * V_red';

end

运行结果

在这里插入图片描述

% Image Compression with Singular Value Decomposition (SVD).
%   This script uses the SVD for Image Compression, analyses the algorithm
%   (also with Information Theory) and visualizes the results.

close all; clear; clc;
tic;
COL = 256; % number of colors in uint8, so 2^8 = 256.


%% Compression

% Original image matrix
Lena_org = imread('Lena.bmp'); % in uint8
Lena = double(Lena_org); % in double

% Call compressing function (and measure performance)
compr = 0.01; % change compr to change quality
tic;
Lena_red = uint8(svd_compress(Lena,compr));
func_time = toc; % compression function execution time
fprintf('Execution time of svd_compress: %d seconds.\n',func_time);

% Save compressed image
imwrite(Lena_red,'ReducedLena.bmp');


%% Analysis of the algorithm

% SVD on the image
[U,S,V] = svd(Lena);

% Extract Singular Values (SVs)
singvals = diag(S);

% Determine SVs to be saved
if compr >= 0 && compr < 1
    % only SVs bigger than compr times biggest SV
    indices = find(singvals >= compr * singvals(1));
elseif compr >= 1 && compr <= length(singvals)
    % only the biggest compr SVs
    indices = 1:compr;
else
    % return error
    error(...
    'Incorrect input arg: compr must satisfy 0 <= compr <= number of Singular Values');
end

% Size of the image
m = size(Lena,1);
n = size(Lena,2);
storage = m*n;
fprintf('Size of image: %d px by %d px, i.e. uses %d px of storage.\n',m,n,storage);

% SVs and reduced storage
r = min([m,n]); % original number of SVs
r_red = length(indices); % to be saved number of SVs
r_max = floor(m*n/(m+n+1)); % maximum to be saved number of SVs for compression
storage_red = m*r_red + n*r_red + r_red;
if compr >= 0 && compr < 1
    % only SVs bigger than compr times biggest SV
    fprintf('The smallest SV chosen to be smaller than %d of the biggest SV.\n',compr);
elseif compr >= 1 && compr <= length(singvals)
    % only the biggest compr SVs
else
    % return error
    fprintf('There was some error before. Analysis cannot continue.\n')
end
fprintf('Out of %d SVs, only %d SVs saved ',r,r_red);
fprintf('(Maximum number of SVs for compression: %d SVs).\n',r_max);
fprintf('Reduced storage: %d px.\n',storage_red);

% Determine made error
error = 1 - sum(singvals(indices))/sum(singvals);
fprintf('Made error: %d.\n',error);
errorImage = Lena_org - Lena_red;

% Entropy
entropy_org = entropy(Lena_org);
fprintf('Entropy of original image: %d bit.\n',entropy_org);
entropy_red = entropy(Lena_red);
fprintf('Entropy of compressed image: %d bit.\n',entropy_red);
entropy_err = entropy(errorImage);
fprintf('Entropy of error image: %d bit.\n',entropy_err);

% 1D Histogram: Original Probability
[orgProb,~,~] = histcounts(Lena_org,1:(COL+1),'Normalization','probability');

% 2D Histogram: Joint Probabiltiy
[jointProb,~,~] = histcounts2(Lena_red,Lena_org,...
    1:(COL+1),1:(COL+1),'Normalization','probability');

% Joint Entropy
p_logp_nan = jointProb.*log2(jointProb);
p_logp = p_logp_nan(isfinite(p_logp_nan));
joint_entropy = -sum(p_logp);
fprintf('Joint entropy: %d bit.\n',joint_entropy);

% Mutual Information
mi = entropy_org + entropy_red - joint_entropy;
fprintf('Mutual information: %d bit.\n',mi);

% Conditional Probability
condProb = jointProb./orgProb;
condProb(isnan(condProb)|isinf(condProb))=0; % all NaN and inf converted to zero
col_sum = sum(condProb,1); % test if condProb really sums up to 1 columnwise


%% Relationship between selcted SVs and ...

numSVals = 1:1:r; %SVs for which the properties are calculated

% ...used storage
storageSV = m*numSVals + n*numSVals + numSVals;

% ...made error and entropies (compressed and error)
displayedError = zeros(size(numSVals));
entropySV = zeros(4,length(numSVals));
    % 1st row entropy of compressed image, 2nd row entropy of error image
    % 3rd row joint entropy, 4th row mutual information
j = 1; % position in the display vectors
for i = numSVals
    % store S in a temporary matrix
    S_loop = S;
    % truncate S
    S_loop(i+1:end,:) = 0;
    S_loop(:,i+1:end) = 0;
    % construct Image using truncated S
    Lena_red_loop = uint8(U*S_loop*V');
    % construct error image
    Lena_err_loop = Lena_org - Lena_red_loop;
    % compute error
    error_loop = 1 - sum(diag(S_loop))/sum(diag(S));
    % add error to display vector
    displayedError(j) = error_loop;
    % compute entropy of compressed image and add to row 1 of display matrix
    entropySV(1,j) = entropy(Lena_red_loop);
    % compute entropy of error image and add to row 2 of display matrix
    entropySV(2,j) = entropy(Lena_err_loop);
    % compute joint entropy of original and compresed image
    [jointProb_loop,~,~] = histcounts2(Lena_org,Lena_red_loop,[COL COL],...
        'Normalization','probability');
    p_logp_nan_loop = jointProb_loop.*log2(jointProb_loop);
    p_logp_loop = p_logp_nan_loop(isfinite(p_logp_nan_loop));
    entropySV(3,j) = -sum(p_logp_loop);
    % compute mutual information of original and compressed image
    entropySV(4,j) = entropy_org + entropySV(1,j) - entropySV(3,j);
    % update position
    j = j + 1;
end


%% Figure 1

fig1 = figure('Name','Images and Histograms',...
    'units','normalized','outerposition',[0 0 1 1]);

% Original image
subplot(2,3,1)
imshow(uint8(Lena))
title('Original image')

% Histogram of original image
subplot(2,3,4)
imhist(Lena_org)
title('Histogram of original image')

% Compressed image
subplot(2,3,2)
imshow(uint8(Lena_red))
title('Compressed image')

% Histogram of compressed image
subplot(2,3,5)
imhist(Lena_red)
title('Histogram of compressed image')

% Error image
subplot(2,3,3)
imshow(uint8(errorImage))
title('Error image')

% Histogram of error image
subplot(2,3,6)
imhist(errorImage)
title('Histogram of error image')


%% Figure 2

fig2 = figure('Name','Joint Histogram',...
    'units','normalized','outerposition',[0 0 1 1]);

% 2D Histogram: Joint PDF
histogram2(Lena_red,Lena_org,1:(COL+1),1:(COL+1),...
    'Normalization','probability','FaceColor','flat')
colorbar
title('Joint Histogram')
xlabel('Compressed image')
ylabel('Original image')
zlabel('Joint Probability')


%% Figure 3

fig3 = figure('Name','Properties over selected Singular Values',...
    'units','normalized','outerposition',[0 0 1 1]);

% Used storage over saved SVs
subplot(2,2,1)
plot(numSVals, storage.*ones(size(numSVals))) % original storage (horizontal)
hold on
plot(numSVals, storageSV)
legend('Original storage', 'Storage of SVD','Location','northwest')
xlabel('Number of saved Singular Values')
ylabel('Used storage [px]')
title('Used storage over saved SVs')

% Compression error over saved SVs
subplot(2,2,3)
plot(numSVals, displayedError)
xlabel('Number of saved Singular Values')
ylabel('Compression error [-]')
title('Compression error over saved SVs')

% Entropies over saved SVs
subplot(2,2,[2,4])
plot(numSVals, entropy_org.*ones(size(numSVals))) % original entropy (horizontal)
hold on
plot(numSVals, entropySV)
legend('Original entropy', 'Compression entropy', 'Error entropy',...
    'Joint entropy','Mutual information','Location','southoutside')
xlabel('Number of saved Singular Values')
ylabel('Entropies [bit]')
title('Entropies over saved SVs')


%% Save figures

saveas(fig1, 'Results.png');
saveas(fig2, 'Joint_Histogram.png');
saveas(fig3, 'Analysis.png');


%% Execution time

execution_time = toc; % total script execution time
fprintf('Total execution time of svd_lena_script: %d seconds.\n',execution_time);

运行结果

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1567150.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

2023最新汽车网络安全报告汇总

2023最新汽车网络安全报告、安全参考架构及指南汇总&#xff0c;供大家学习参考。https://t.zsxq.com/18RkG260k 汽车信息安全法律法规及标准全景图V3.2.pdf 车载智能计算基础平台参考架构2.0.pdf 车载智能计算芯片白皮书(2023版).pdf 智能驾驶行为安全评价方法发布版.pdf 智能…

大数据实验统计-1、Hadoop安装及使用;2、HDFS编程实践;3、HBase编程实践;4、MapReduce编程实践

大数据实验统计 1、Hadoop安装及使用&#xff1b; 一&#xff0e;实验内容 Hadoop安装使用&#xff1a; 1&#xff09;在PC机上以伪分布式模式安装Hadoop&#xff1b; 2&#xff09;访问Web界面查看Hadoop信息。 二&#xff0e;实验目的 1、熟悉Hadoop的安装流程。 2、…

【STM32嵌入式系统设计与开发】——16InputCapture(输入捕获应用)

这里写目录标题 STM32资料包&#xff1a; 百度网盘下载链接&#xff1a;链接&#xff1a;https://pan.baidu.com/s/1mWx9Asaipk-2z9HY17wYXQ?pwd8888 提取码&#xff1a;8888 一、任务描述二、任务实施1、工程文件夹创建2、函数编辑&#xff08;1&#xff09;主函数编辑&#…

进制转换器(C语言)

目录 1问题&#xff1a; 输入任意进制的数值&#xff0c;可以转换成任意进制的数值&#xff08;2到36进制&#xff09;; 2思路&#xff1a; 3代码&#xff1a;&#xff08;需要运用到数据结构栈的知识&#xff09; 4运行结果&#xff1a; 1问题&#xff1a; 输入任意进制的数…

使用 LLMLingua-2 压缩 GPT-4 和 Claude 提示

原文地址&#xff1a;Compress GPT-4 and Claude prompts with LLMLingua-2 2024 年 4 月 1 日 向大型语言模型&#xff08;LLM&#xff09;发送的提示长度越短&#xff0c;推理速度就会越快&#xff0c;成本也会越低。因此&#xff0c;提示压缩已经成为LLM研究的热门领域。 …

RK3568 RTC驱动实验

RK3568 RTC驱动实验 1. RTC简介 ​ RTC 也就是实时时钟&#xff0c;用于记录当前系统时间&#xff0c;对于 Linux 系统而言时间是非常重要的&#xff0c;使用 Linux 设备的时候也需要查看时间。RTC是Linux的时间系统。 ​ RTC 设备驱动是一个标准的字符设备驱动&#xff0c;…

R语言数据挖掘:随机森林(1)

数据集heart_learning.csv与heart_test.csv是关于心脏病的数据集&#xff0c;heart_learning.csv是训练数据集&#xff0c;heart_test.csv是测试数据集。要求&#xff1a;target和target2为因变量&#xff0c;其他诸变量为自变量。用决策树模型对target和target2做预测&#xf…

ESP32学习---ESP-NOW(一)

ESP32学习---ESP-NOW&#xff08;一&#xff09; 官网简介arduino 官网简介 首先看官网的介绍&#xff1a;https://www.espressif.com.cn/zh-hans/solutions/low-power-solutions/esp-now ESP-NOW 是乐鑫定义的一种无线通信协议&#xff0c;能够在无路由器的情况下直接、快速…

使用deepspeed,transformers,safetensor中常见的训练精度,共享权重问题

使用deepspeed可能需要注意精度问题 混合精度&#xff0c;LayerNorm 虽然deepspeed有混合精度训练的功能&#xff0c;但是对于网络上各种奇奇怪怪的代码的DIY转化中&#xff0c;他还是很弱小的。它的精度问题&#xff0c;使用deepspeed如果模型中有部分模型使用的是half精度&a…

Ubuntu22.04安装Anaconda

一、下载安装包 下载地址&#xff1a;https://www.anaconda.com/download#Downloads 参考&#xff1a;Ubuntu下安装Anaconda的步骤&#xff08;带图&#xff09; - 知乎 下载Linux 64-Bit (x86) installer 二、安装 在当前路径下&#xff0c;执行命令&#xff1a; bash Ana…

机器学习——几个线性模型的简介

目录 形式 假设 一元回归例子理解最小二乘法 多元回归 广义线性回归 对数线性回归 逻辑回归 线性判别分析 形式 线性说白了就是初中的一次函数的一种应用&#xff0c;根据不同的(x,y)拟合出一条直线以预测&#xff0c;从而解决各种分类或回归问题&#xff0c;假设有 n …

外链工具源码版V1

请将zip文件全部解压缩即可访问&#xff01; 源码全部开源&#xff0c;支持上传二级目录访问 #已更新增加大量高质量外链&#xff08;若需要增加修改其他外链请打开txt文件&#xff09; #修复优化页面端 源码下载地址&#xff1a;外链工具源码版V1

基于k8s的web服务器构建

文章目录 k8s综合项目1、项目规划图2、项目描述3、项目环境4、前期准备4.1、环境准备4.2、ip划分4.3、静态配置ip地址4.4、修改主机名4.5、部署k8s集群4.5.1、关闭防火墙和selinux4.5.2、升级系统4.5.3、每台主机都配置hosts文件&#xff0c;相互之间通过主机名互相访问4.5.4、…

Rust---复合数据类型之枚举、数组

目录 枚举的使用Option 枚举数组的使用输出结果 枚举&#xff08;Enum&#xff09;&#xff1a;表示一个类型可以有多个不同的取值。枚举类型可以包含不同的变体&#xff08;variants&#xff09;&#xff0c;每个变体可以有不同的数据类型。 枚举的使用 enum Direction {Up,…

Linux-Arm GDB调试(本地和远程)

目录 问题描述 已有coredump 没有coredump 小结 问题描述 Linux本机调试使用GDB非常方便&#xff0c;但嵌入式Linux设备资源有限&#xff0c;通常并没有交叉编译工具&#xff0c;那嵌入式设备上的应用发生问题如何查找问题&#xff1f;通常IDE有远程DEBUG功能&#xff0c;这…

【计算机视觉】四篇基于Gaussian Splatting的SLAM论文对比

本文对比四篇论文&#xff1a; [1] Gaussian Splatting SLAM [2] SplaTAM: Splat, Track & Map 3D Gaussians for Dense RGB-D SLAM [3] Gaussian-SLAM: Photo-realistic Dense SLAM with Gaussian Splatting [4] GS-SLAM: Dense Visual SLAM with 3D Gaussian Splatting …

MySQL数据库 数据库基本操作(一):数据库的认识与基本操作

1. 数据库的基本认识 1.1 什么是数据库 专家们设计出更加利于管理数据的软件——数据库&#xff0c;它能更有效的管理数据。数据库可以提供远程服务&#xff0c;即通过远程连接来使用数据库&#xff0c;因此也称为数据库服务器。 1.2 数据库的分类 数据库可以大体分为:关系…

基于Python的简单颜色替换

当我们临时需要改变一个照片的颜色&#xff0c;使其符合我们想要的主题色时&#xff0c;对于不会PS的我就只能使用一下Python来实现这个简单的过程 比如我想要中国农大农学院的院徽&#xff0c;但在官网上提取出来的图片是白色的 而我想要符合农学主题的绿色&#xff0c;将图片…

产品经理知识地图:与NPDP国际资格认证知识体系相吻合的实践探索

在数字化时代的浪潮下&#xff0c;产品经理的角色愈发关键。作为连接市场、技术与用户的桥梁&#xff0c;产品经理需要拥有全面的知识体系与多元化的能力。本文旨在构建与NPDP产品经理国际资格认证知识体系相吻合的产品经理知识地图&#xff0c;并结合实际案例&#xff0c;探讨…

VSCode安装及Python、Jupyter插件安装使用

VSCode 介绍 Visual Studio Code&#xff08;简称VSCode&#xff09;是一个由微软开发的免费、开源的代码编辑器。VSCode是一个轻量级但是非常强大的代码编辑器&#xff0c;它支持多种编程语言&#xff08;如C,C#&#xff0c;Java&#xff0c;Python&#xff0c;PHP&#xff0…