- imshow 整理关于复数

如果用imshow(a),而且a是复数矩阵,则按照a的实部处理。
用imshow(abs(a)),则是按a的模处理。

f = imread('timg.jpg');
impixelinfo %根据鼠标光标显示位置和图像值I = rgb2gray(f); %这里最好是转换成灰度图像处理,不然。。。貌似结果会变得非常奇怪。
I = im2double(I);
imshow(I)
imshow(I,[])   %I中最大的作为255,最小的作为0
imshow(I,[2 50])  %用指定的灰度范围 [low high]显示灰度图像 I。
%显示结果,图像中灰度值等于或低于low的都将用黑色显示,而灰度值大于等于high的都显示为白色,

- 循环读取多张图片

循环读取图片
第一种方法①

List =dir('*.jpg');
%如需其它图片格式支持,可以自己【重载dir()】函数,实现查找所有图片文件的功能,
%如果图片是其它路径,可以用 ["路径" ".扩展名"] 字符串来实现。
k =length(dList);
for i=1:1:k
image_data{i}=imread(dList(i).name);
end

第二种方法②

I=ones(8,5);
q=reshape(49:56,8,1);
I(:,1)=q;
I(:,2)='.';
I(:,3)='b';
I(:,4)='m';
I(:,5)='p';
L=setstr(I); %将ASCII码转为字符串;

第三种方法③

images= [ ];
fo r i= 1:M
str= strcat ('D: \MATLAB\work\', int2str(i) , ’.bmp’) ; % 连接字符串形成图像的文件名。
img= imread(str);
[rows cols]= size(img) ; % 获得图像的行和列值。
temp= reshape ( img, rows*cols, 1) ; % 创建一个(N1*N2)×1 矩阵。
images= [ images temp ]; % 完成循环后的images 矩阵是一个(N 13 N 2) ×M 矩阵。
end

这是搜集整理的知识。
上述三种方法中,第一种主要利用dir()函数,获得文件夹内图片的信息,然后创建一个元胞数组,将图片文件信息送入元胞数组
第二种方法是已知图片文件名,并且按数字顺序排列,然后利用数字和字符串之间的转换来进行。
第三种方法利用字符串连接函数strcat()函数巧妙运用循环实现图片的连续读入。

- 移动矩阵内部元素

circshift(A,[2 3])     % A矩阵向下移动2,向右移动1, 整体移动,挤走的占据多出的位置

- 处理数据,同时读取多个文件

clear
clc
%%
% Onm=cell(1,7);
getfilename=ls('C:\Users\feifei\Desktop\*.xl*'); %取目录下所有excel文件的文件名(.xls或.xlsx)
filename = cellstr(getfilename); %将字符型数组转换为cell型数组
num_of_files = length(filename); %excel文件数目
for i=1:num_of_files %循环读入excel数据并存入结构体database中
database(i) = struct('Name',filename{i},'Data',xlsread(filename{i}));
end%%
for i=1:num_of_files
database(i).Data=mean(database(i).Data,2);xx=1551:1575;%   subplot(2,4,i); %分成2×2区域且指定1号为活动区%figure('Name',filename{i});plot(xx,database(i).Data,'linewidth',3,'markersize',16)title(filename{i})    %%%axis ([1550 1570 -1 2]);  xtickk=1550:10:1575%%set(gca,'xticklabel',xtickk);
end

- 找到二维矩阵中最大的数,从小到大一维排列

clc
clear
a=[1 34 5; 5 5 66; 6 89 3];%  方法1
s=size(a)
b=reshape(a , 1 ,s(1)*s(2))
c=sort(b)% 方法2
% [c,index]=sort(a(:),'descend')
% [Xaxis,Yaxis]=find(c>=10)

- 找出2维中大于100的的数,求和

%找出2维中大于100的的数,求和clear
clcI=imread('C:\Users\Administrator\Desktop\readtest\timg.jpg');
if ndims(I) == 3%如果图片是3维(彩图)I = rgb2gray(I);%转成灰图
end %结束[row,col]=find(I>=100);
aaa=[row,col];             %aaa是大于100的位置
[irow icol]=size(col);     %为了把irow拿出来,就是一共有多少个大于100的数,有多少行就有多少个
% imshow(I); %展示图片
I = double(I);all=0;
for i=1:irowall=I(row(i),col(i))+all;
end    all

- 二维矩阵中,把设定的圆中的数取出来,剩下的为0


% 功能:在一个二维矩阵中,把设定的圆中的数取出来,剩下的为0
% 原理:逐个计算每个点和圆心的距离,大于半径则舍弃,小于等于半径则保留function [get_cir]=get_matrix_circle(origin,cir_r,cir_center)
%输入参数介绍:
%origin   一个二维图像, 最好是在0-1之间的double类型的
%cir_r    设定的圆半径,一个常数
%cir_center  圆心位置行列 eg [5 5] [行 列]%输出参数介绍:
%输出get_cir 是把输入的图像以及制定的圆内的数保留,圆外数为0origin_size=size(origin);
origin_r=origin_size(1); %总行数
origin_c=origin_size(2); %总列数get_cir=[];     %取出的圆内元素值
for i=1:origin_rfor j=1:origin_ctemp=[i j];if norm(cir_center-temp)<=cir_r  %norm为范数函数,默认2-范数,用来求两点距离get_cir(i,j)=origin(i,j);   %符合条件的元素值elseget_cir(i,j)=0;  %没有在园内的,则为0endend
end

- show变成百分数

%%变成百分数
x=2.1/3;
disp([num2str(x*100),'%'])

- 多张图读取,截取,求梯度

clear
clc
dList =dir('E:\2017-09-11\2\*.jpg');
%如需其它图片格式支持,可以自己【重载dir()】函数,实现查找所有图片文件的功能,
%如果图片是其它路径,可以用 ["路径" ".扩展名"] 字符串来实现。
len =length(dList);
image_data=cell(1,len); %定义一个元胞数组存放图像
for i=1:1:lendList(i).name=strcat('E:\2017-09-11\2\',dList(i).name); %图片名和路径名的字符串连接起来image_data{i}=imread(dList(i).name);%figure,imshow(image_data{i});title(dList(i).name); %展示图片if ndims(image_data{i}) == 3%如果图片是3维(彩图)image_data{i} = rgb2gray(image_data{i});%转成灰图end %结束Inew=image_data{i}(218:500,238:500);% 2文件夹Inewdou=double(Inew);[x,y]=gradient(Inewdou);   %获取梯度t=sqrt(x.^2+y.^2);  G=Inewdou;G(t>=2)=0;           %梯度提取边缘 画黑G(t<2)=255;G=uint8(G);% figure,imshow(G);title(dList(i).name);all(i)=sum(G(:)==0);
end
xx=1:len;
plot(xx,all,'.-','linewidth',1,'markersize',16)
all=all'

- 傅里叶频域一块也可以复原

% 测试了傅里叶变化中
% 频率域中取一小块也能还原出原来的图像
% 傅里叶域中的高频部分还原出来的图像的梯度大的部分,边缘部分
% 傅里叶域中的低频部分还原出来的图像的梯度小的部分I = imresize(imread('Fig0206(a)(rose-original).tif'),[256,256]);
J  =fftshift(fft2(I));%复数物的傅里叶谱
filter=zeros(256);
% filter([1:64,192:256],[1:64,192:256])=1;
filter([120:140],[120:140])=1;final = filter .* J;
ori = ifft2 (ifftshift(final));
figure,imshow(ori,[])

- 关于ifftshift的问题


clc
clear
%实际的强度
Image_abs= imresize(imread('cameraman.tif'),[256,256]);
Image_abs = mat2gray(Image_abs);
%实际的相位
Image_angle= imresize(imread('westconcordorthophoto.png'),[256,256]);
% Image_angle= zeros(256);
Image_angle = 2*pi*mat2gray(Image_angle)-pi;
%复数的输入实际图像
Image = Image_abs.*exp(1i.*Image_angle);
%%  测试一
% 事实说明
% 开始变化到频谱加上fftshift的话
% 在变化到物空间的时候要先加上ifftshift
% 否则,相位会变坏。振幅不受影响。Image_fft=fftshift(fft2(Image));%物的频谱image_1=ifft2(ifftshift(Image_fft));%
image_2=ifft2((Image_fft));%figure,imshow(angle(image_1),[]);
figure,imshow(angle(image_2),[]);
figure,imshow(abs(image_1),[]);
figure,imshow(abs(image_2),[]);%%  测试二    下面是别的大佬waller写的函数也很好用
F = @(x) ifftshift(fft2(fftshift(x))); %Fourier Transform
Ft = @(x) ifftshift(ifft2(fftshift(x))); %Inverse Fourier Transformimage_fft=F(Image);%物的频谱
image_1=Ft(image_fft);%
figure,imshow(log(abs(image_fft)),[]);figure,imshow(log(angle(image_fft)),[]);
figure,imshow(abs(image_1),[]);figure,imshow(angle(image_1),[]);

- 把一幅图的数值范围拉伸到minVal~maxVal之间

adjustScale.m文件

function outputMatrix = adjustScale( inputMatrix, minVal, maxVal )
%把一幅图的数值范围拉伸到minVal~maxVal之间
minmum=min(min(inputMatrix));
maxmum=max(max(inputMatrix));
outputMatrix=(inputMatrix-minmum)/(maxmum-minmum);
outputMatrix=minVal+outputMatrix*(maxVal-minVal);

- 把从文件夹中读出很多文件的顺序按照正常命名的1 2 3…的顺序

下面例子:
把imglist 这个结构体中的name正常重新排序
因为sortnat这个函数的输入输出是元胞数组,
所以先转化为元胞,再还原回imglist

imglist = dir([filedir,'*.tif']);
%把读取到的文件夹的数据顺序按照文件名的正常顺序
nameCell = cell(length(imglist),1);
for i = 1:length(imglist)nameCell{i} = imglist(i).name;
end
nameCell = sortnat(nameCell);
for i = 1:length(imglist)imglist(i).name = nameCell{i};
end

sortnat.m如下:

function [CoS,ind,ChA,NuA] = sortnat(CoS,varargin)
% Customizable natural-order sort of a cell array of strings.
%
% (c) 2012 Stephen Cobeldick
%
% ### Function ###
%
% Sort the strings in a cell array of strings by character order (ASCII)
% and the value of any numeric tokens.
%
% By default sorts case-insensitive ascending, with integer numeric tokens.
% Optional inputs may be used control the format of the numeric tokens
% within the strings (see 'Tokens'), case sensitivity and sort direction.
%
% Syntax:
%  SortedCellStr = sortnat(CellStr)
%  [SortedCellStr,SortIndex] = sortnat(CellStr,...);
%  [...] = sortnat(CellStr,RegExp)
%  [...] = sortnat(CellStr,RegExp,Case)
%  [...] = sortnat(CellStr,RegExp,Case,Descend)
%  [...] = sortnat(CellStr,RegExp,Case,Descend,Format)
%
% See also SORT SORTROWS UNIQUE CELLSTR REGEXP SSCANF
%
% ### RegExp Tokens ###
%
% # A numeric token consists of some combination of digits, may optionally
%   include a +/- sign, decimal point, exponent, etc. The numeric tokens
%   must be able to be parsed by "sscanf" (*default format '%f'), and may
%   be defined by the optional "regexp" regular expression input, eg:
%
%   Regular Expression Example: | Matches Numeric Token:
%   ----------------------------|---------------------------------
%                         '\d+' | integer (*default).
%   ----------------------------|---------------------------------
%                   '(-|+)?\d+' | integer with optional +/- sign.
%   ----------------------------|---------------------------------
%                 '\d+(\.\d+)?' | integer or decimal.
%   ----------------------------|---------------------------------
%                       \d+|inf | integer or infinite value.
%   ----------------------------|---------------------------------
%               '(-|+)\d+\.\d+' | decimal with +/- sign.
%   ----------------------------|---------------------------------
%                     '\d+e\d+' | exponential.
%   ----------------------------|---------------------------------
%     '[1-9]\d*|(?<=0?)0(?!\d)' | integer excluding leading zeros.
%
% # A character is any other single character: all other characters not
%   matching the "regexp" pattern, including space & non-printing characters.
%
% ### Examples (comparison with "sort") ###
%
% # Integer numeric tokens:
%
% A = {'File2.txt','File10.txt','File1.txt'};
% sort(A)
%  ans = {'File1.txt','File10.txt','File2.txt'}
% sortnat(A)
%  ans = {'File1.txt','File2.txt','File10.txt'}
%
% # Integer or decimal numeric tokens, possibly with +/- signs:
%
% B = {'File102.txt','File11.5.txt','File-1.4.txt','File+0.3.txt'};
% sort(B)
%  ans = {'File+0.3.txt','File-1.4.txt','File102.txt','File11.5.txt'}
% sortnat(B,'(-|+)?\d+(\.\d+)?')
%  ans = {'File-1.4.txt','File+0.3.txt','File11.5.txt','File102.txt'}
%
% # Integer or decimal numeric tokens, possibly with an exponent:
%
% C = {'A_0.56e+07','A_4.3E2','A_10000','A_9.8'}
% sort(C)
%  ans = {A_'0.56e+07','A_10000','A_4.3E2','A_9.8'}
% sortnat(C,'\d+(\.\d+)?(e(+|-)?\d+)?')
%  ans = {'A_9.8','A_4.3E2','A_10000','A_0.56e+07'}
%
% # ASCII order (including non-printing characters):
% sortnat(CellStr,'[]',true);
%
% ### Inputs and Outputs ###
%
% Outputs:
%   Out = CellOfStrings, InC sorted into natural-order, same size as InC.
%   ind = Numeric array, such that OutCoS = InCoS(ind), same size as InC.
% For debugging: each row is one string, linear-indexed from InC:
%   ChA = Character array, all separate non-numeric characters.
%   NuA = Numeric array, "sscanf" converted numeric values.
%
% Inputs:
%   InC = CellOfStrings, whose string elements are to be sorted.
%   tok = String, "regexp" numeric token extraction expression, '\d+'*.
%   cse = Logical scalar, true/false* -> case sensitive/insensitive.
%   dsc = Logical scalar, true/false* -> descending/ascending sort.
%   fmt = String, "sscanf" numeric token conversion format, '%f'*.
%
% An empty input [] uses the default input option value (indicated *).
%
% Outputs = [Out,ind,chr,num]
% Inputs = (InC,tok*,cse*,dsc*,fmt*)DfAr = {'\d+',false,false,'%f'}; % *{tok,cse,dsc,fmt}
DfIx = ~cellfun('isempty',varargin);
DfAr(DfIx) = varargin(DfIx);
[tok,cse,dsc,fmt] = DfAr{1:4};
%
CsC = {'ignorecase','matchcase'};
SrS = ['(',tok,')|.'];
%
% Split strings into tokens:
[MtE,ToX] = regexp(CoS(:),SrS,'match','tokenextents',CsC{1+cse});
%
Clx = cellfun('length',MtE);
Cly = numel(MtE);
Clz = max(Clx);
%
% Initialize arrays:
ChA = char(zeros(Cly,Clz));
ChI = false(Cly,Clz);
MtC = cell(Cly,Clz);
NuA = NaN(Cly,Clz);
NuI = false(Cly,Clz);
%
% Merge tokens into cell array:
ind = 1:Cly;
for n = ind(Clx>0)cj = cellfun('isempty',ToX{n});ChI(n,1:Clx(n)) = cj;NuI(n,1:Clx(n)) = ~cj;MtC(n,1:Clx(n)) = MtE{n};
end
% Transfer tokens to numeric and char arrays:
ChA(ChI) = [MtC{ChI}];
NuA(NuI) = sscanf(sprintf('%s ',MtC{NuI}),fmt);
%
if cseMtC = ChA;
elseMtC = lower(ChA);
end
%
MoC = {'ascend','descend'};
MoS = MoC{1+dsc};
%
% Sort each column of characters and numeric values:
ei = (1:Cly)';
for n = Clz:-1:1% Sort char and numeric arrays:[~,ci] = sort(MtC(ind,n),MoS);[~,ni] = sort(NuA(ind,n),MoS);% Relevant indices only:cj = ChI(ind(ci),n);nj = NuI(ind(ni),n);ej = ~ChI(ind,n) & ~NuI(ind,n);% Combine indices:if dscind = ind([ci(cj);ni(nj);ei(ej)]);elseind = ind([ei(ej);ni(nj);ci(cj)]);end
end
%
ind = reshape(ind,size(CoS));
CoS = reshape(CoS(ind),size(CoS));
%----------------------------------------------------------------------End!

- 模拟透镜成像过程-频域


clc
clear
%本例完成透镜成像演示(相干照明衍射受限系统,不考虑像差和离焦)
%改变透镜的孔径大小D,可以观察到一些有意义的结果
a=imread('分辨率板_1.bmp');%调入图像
a=double(a(:,:,1));
lamda=6328*10^(-10);k=2*pi/lamda;%波矢
D=0.04;%透镜的孔径
f=0.4;%透镜的焦距
figure,imshow(a,[])
[c,r]=size(a);zo=1.2;          %图像到透镜的距离,单位:米,可以改变
zi=zo*f/(zo-f);  %透镜到观察屏的距离,单位:米,可以改变
Lo=0.005;         %物的大小% maxfrequency=D/2/lamda/zo;    %截止频率(阿贝观点)
% kethi=linspace(-1./2./Lo,1./2./Lo,c).*c;
% nenta=linspace(-1./2./Lo,1./2./Lo,r).*r;
% [kethi,nenta]=meshgrid(kethi,nenta); %物的频率范围maxfrequency=D/2/lamda/zi;    %截止频率(瑞利观点)
Li=Lo*zi/zo;
kethi=linspace(-1./2./Li,1./2./Li,c).*c;
nenta=linspace(-1./2./Li,1./2./Li,r).*r;
[kethi,nenta]=meshgrid(kethi,nenta); %物的频率范围H=zeros(r,c);   %生成传递函数
for n=1:rfor m=1:cif kethi(n,m).^2+nenta(n,m).^2<=maxfrequency.*maxfrequency;H(n,m)=1;endend
end
figure,imshow(H,[]);title('传递函数')Gg=fftshift(fft2(a));%物的频谱
Gi=Gg.*H;            %像的频谱
Ui=ifft2(Gi);
Ii=Ui.*conj(Ui);     %在透镜上的光强分布
figure,imshow(Ii,[]),title('透镜上的光强分布');
% colormap(pink)

matlab常用代码总结相关推荐

  1. Matlab常用代码---持续更新

    Matlab中的一些常用代码---持续更新 1. 获取当前的工作目录路径:添加文件夹到工作路径 2. 获取某个.m文件的绝对路径 3. 使用随机颜色进行可视化 1. 获取当前的工作目录路径:添加文件夹 ...

  2. matlab常用代码(读取文件、批量导入数据、与或非)

    学习matlab使用过程中遇到的各种常见小操作,放在这里权当记录,持续更新中.包括批量导入数据.读取/写入不同类型的文件.与或非.cell.randperm的使用等 一.常见函数或小技巧 1. 记录程 ...

  3. matlab常用的代码,matlab常用代码

    1.将数组数据存到text文件中 fid=fopen('test1.txt','wt'); %写的方式打开文件(若不存在,建立文件): fprintf(fid,'%d ',Scan_Pha); % % ...

  4. python matlab 多条曲线 单位_【基础篇】MATLAB科研制图常用代码命令

    最近更新了不少关于数学建模算法与机器学习的博客,今天我来写写关于科研制图的MATLAB常用命令,众所周知,在未来的科研生涯中,只要是学工科的同学们,MATLAB都是大家必学的工具之一,而发paper中 ...

  5. Matlab常用绘图代码

    Matlab常用绘图代码 包含常用分界线绘制.图片局部填充以及多图例绘制说明. 绘制横线.竖线 plot([0,1],[1,1],'r' ,'linewidth',2) %画横线 plot([1,1] ...

  6. matlab系统辨识工具箱原理,matlab常用工具箱介绍

    怎么使用matlab系统辨识工具箱 如果是系统自带的,你可以直接用,如果是外部的或者是自编的你需要先把文件夹拷贝到tools文件夹下,再设置路径. Matlab常用工具箱介绍(英汉对照)Matlab ...

  7. Matlab 常用的图像处理方法

    文章目录 Matlab 常用的图像处理方法 RGB转灰度 噪声添加 滤波 中值滤波 均值滤波 sobel算子处理 图像形态学运算 Reference Matlab 常用的图像处理方法 RGB转灰度 R ...

  8. Matlab常用操作入门及电力电子系统仿真

    引言 刚刚比较系统地学了一遍Matlab(主要是基础知识和电力电子方面的使用),专门撰写此文,写一下自己对于matlab及Power electronic方面的应用的总结和心得. Matlab入门 因 ...

  9. 4.MATLAB常用命令

    MATLAB命令 本节的内容将提供常用的一些MATLAB命令. 在之前的篇章中我们已经知道了MATLAB数值计算和数据可视化是一个交互式程序,在它的命令窗口中您可以在MATLAB提示符"&g ...

最新文章

  1. Qt 连接达梦数据库
  2. UILable文字不居中问题
  3. 列举ospf的5种报文类型_9种语言的应用场景,程序员的候选清单,你最看好哪一门语言...
  4. 二叉树的基本理论知识
  5. 【每日一题】8月7日题目精讲—双栈排序
  6. lodash round
  7. 智能车复工日记【N】:图像处理——环岛debug记录(持续更新)
  8. 多浏览器判断,切换及使用
  9. java定义一个类显示没有_Java 中的每个类都至少有一个构造方法,一个类中如果没有定义构造方法,系统会自动为这个类创建一个默认的构造方法。_学小易找答案...
  10. 小米组织架构再调整:手机部成立参谋部 朱磊出任参谋长
  11. UI设计中的黄金分割率,实用案例适合临摹学习
  12. 【Express】—get根据不同的参数返回不同的数据
  13. 【动态规划笔记】01背包问题:leetcode415 分割等和子集
  14. 网络安全未来发展怎么样?
  15. 寂静岭2java攻略_寂静岭2攻略
  16. 明日之后 找不到服务器,《明日之后》无法连接服务器怎么解决 服务器无法连接解决方法...
  17. Linux打印当前目录
  18. 荒岛求生游戏显示服务器不行,荒岛求生连接服务器失败怎么办
  19. 武夷山停排事件内幕调查
  20. DRM——学习篇0:概念认识

热门文章

  1. DataGrid Web Control 连载之九
  2. laravel中Request、Session、Response、Middelware
  3. python里pickle模块
  4. WebService 学习之路(一):了解并使用webService
  5. MySQL基础学习过程
  6. JavaScript中Exists函数
  7. 第二阶段冲刺第六天(6月5号)
  8. 单链表基本操作(可执行程序),二级指针使用必要性的初步理解
  9. 几种常用通信协议:IIC协议、SPI协议、UART协议
  10. 支付宝人脸数据被共享?李开复道歉