matlab常用代码总结

- 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
clc

I=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:irow
    all=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 是把输入的图像以及制定的圆内的数保留,圆外数为0

origin_size=size(origin);
origin_r=origin_size(1); %总行数
origin_c=origin_size(2); %总列数

get_cir=[];     %取出的圆内元素值
for i=1:origin_r
    for j=1:origin_c
        temp=[i j];
        if norm(cir_center-temp)<=cir_r  %norm为范数函数,默认2-范数,用来求两点距离
            get_cir(i,j)=origin(i,j);   %符合条件的元素值
        else
            get_cir(i,j)=0;  %没有在园内的,则为0
        end
    end
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:len
    dList(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 Transform

image_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 cse
    MtC = ChA;
else
    MtC = 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 dsc
        ind = ind([ci(cj);ni(nj);ei(ej)]);
    else
        ind = 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:r
   for m=1:c
      if kethi(n,m).^2+nenta(n,m).^2<=maxfrequency.*maxfrequency;
         H(n,m)=1;
      end
   end
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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值