您的位置:首页 > 编程语言 > MATLAB

matlab图片扭曲

2015-07-01 16:21 465 查看
需要按一定规律扭曲后图片,以下为整理的两种方法。

原图:



波纹扭曲

扭曲结果:



clear all;close all;clc;

img=imread('lena.jpg');
[h w]=size(img);

wave=[10,100]; %[幅度,周期]
newh=h+2*wave(1);
neww=w+2*wave(1);
rot=0;

for i=1:10
imgn=zeros(newh,neww);

rot=rot+0.2;
for y=1:newh
for x=1:neww

yy=round((y-wave(1))-(wave(1)*cos(2*pi/wave(2)*x+rot)));    %依然是逆变换
xx=round((x-wave(1))-(wave(1)*cos(2*pi/wave(2)*y+rot)));

if yy>=1 && yy<=h && xx>=1 && xx<=w
imgn(y,x)=img(yy,xx);
end

end
end

figure(1);
imshow(imgn,[]);

imgn(:,:,2)=imgn;       %生成gif图片
imgn(:,:,3)=imgn(:,:,1);
[I,map]=rgb2ind(mat2gray(imgn),256);

    if i==0
      imwrite(I,map,'re.gif','Loopcount',inf,'DelayTime',1.5);
    else
      imwrite(I,map,'re.gif','DelayTime',0.1,'WriteMode','Append');
    end
end


使用RandStream生成随机形变



function deform
M = double(imread('lenag2.png'));
[F,sx0,sy0]  = randomdeform(M,100,6);
figure(1); showvector(sx0,sy0,4,3,lim); drawnow;
figure(2); showgrid(sx0,sy0,4,lim);drawnow;
figure(3),imshow(F,[])
end

function [I,sx,sy] = randomdeform(I,maxdeform,sigma)

if nargin<2; maxdeform = 3; end; % max 3 pixels of deformation
if nargin<3; sigma     = 3; end; % max smooth on 3 pixels

% Create random deformation
s  = RandStream.create('mt19937ar','seed',1);
RandStream.setGlobalStream(s);
% always same random numbers
sx = maxdeform * 2*(rand(size(I))-0.5);
sy = maxdeform * 2*(rand(size(I))-0.5);

% Smooth deformation
sx = imgaussian(sx,sigma);
sy = imgaussian(sy,sigma);

% Interpolate updated image
I = iminterpolate(I,sx,sy);

end

function I = imgaussian(I,sigma)

if sigma==0; return; end; % no smoothing

% Create Gaussian kernel
radius = ceil(3*sigma);
[x,y]  = ndgrid(-radius:radius,-radius:radius); % kernel coordinates
h      = exp(-(x.^2 + y.^2)/(2*sigma^2));
h      = h / sum(h(:));

% Filter image
I = imfilter(I,h);

end

function I = iminterpolate(I,sx,sy)

% Find update points on moving image
[x,y] = ndgrid(0:(size(I,1)-1), 0:(size(I,2)-1)); % coordinate image
x_prime = x + sx; % updated x values (1st dim, rows)
y_prime = y + sy; % updated y values (2nd dim, cols)

% Interpolate updated image
I = interpn(x,y,I,x_prime,y_prime,'linear',0); % moving image intensities at updated points

end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: