How to combine this Matlab code? It's shifting a picture using matrices

Viewed 56

Currently struggling with this code, cannot combine it, have been modifying it for hours. It's supposed to be a script that, when ran, shifts a picture horizontally and vertically. I have the code for the horizontal shift and the vertical shift, and separately, they both run and do what they're supposed to do, however, when I try to combine the two, I cannot get it to work at all. I have modified variables and looked at examples of doing this, but none of the examples have helped with combing the code successfully. Code is below.

Horizontal:

X=imread('photo1.jpg'); 
X_double=double(X);
X_gray = 0.3*X_double(:,:,1) + 0.3*X_double(:,:,2) + 0.3*X_double(:,:,3); 
imagesc(uint8(X_gray))
colormap('gray')
[m,n]=size(X1);
r=240;
E=eye(n);
T=zeros(n,n);
T(:,1:r)=E(:,n-(r-1):n);
T(:,r+1:n)=E(:,1:n-r);
X_shift=X1*T;
imagesc(uint8(X_shift));
colormap('gray');

Vertical:

[m,n] = size(X1); 
r = 100;
E = eye(m);
T = zeros(m);
T(1:r,:) = E(m-(r-1):m,:);
T(r+1:m,:) = E(1:m-r,:);
X_shift = T*X_gray ;
imagesc(uint8(X_shift)); 
colormap('gray');

Yes there are easier ways to do this, but this is how I'm supposed to be doing this. Any help would be appreciated, thank you.

1 Answers

You can use circshift to do that:

X=imread('peppers.png');
dx = -200;
dy = 100;
Y = circshift(X, [dy dx 0]);
imshow(Y)

enter image description here

As an additional note about your code, use rgb2gray for converting images to grayscale.

Related