- #1
gnome
- 1,041
- 1
OK here I am, bigshot, giving out advice on how to rotate an image when I'm just trying to learn that myself.
I'm trying to do this in Matlab; it's rotating, but for some reason the rotated image is acquiring a black background and has various lines and dots superimposed on it. Can anyone tell me why?
Here's the code:
Images are attached. triangles.png is the original image. tri.png is just the red layer of that file; that's the array I'm rotating. newtri.png is the result.
Edit: I just noticed that tri.png got rotated somehow in the process of uploading, so it wasn't oriented the same as the original image. Now it's OK.
Edit: added more comments to the code (everything starting with % is a comment)
I'm trying to do this in Matlab; it's rotating, but for some reason the rotated image is acquiring a black background and has various lines and dots superimposed on it. Can anyone tell me why?
Here's the code:
Code:
% rotation.m
% reads in and rotates a figure in file triangles.png
a = imread('triangles.png');
image(a); % this just displays the original image
pause;
close; % this closes it
[rows cols layers] = size(a); % this declares 3 variables named rows, cols
% & layers & assigns to them the dimensions of array a
s = min(rows,cols);
%% want to make sure the new image is square, just for convenience
rows=s;
cols=s;
%% declare a 32-bit int vector p (1 x 2) to hold the coordinates of the new point, initialized (0 0)
p=int32(zeros(1,2));
%% for simplicity, I will only deal with one color so define two 2D matrices, size rows x cols,
%% type double to allow multiplication, initialized to all 0s
b = double(zeros(rows,cols));
c = double(zeros(rows,cols));
%% loop through the array, copying just the red layer of a to the corresponding pixels of b
for row = 1:rows,
for col = 1:cols,
b(row,col)=a(row,col,1);
end
end
%% define the transformation matrix t
t = [ cos(pi/4) -sin(pi/4); sin(pi/4) cos(pi/4)];
%% now loop through the arrays computing rotated & shifted coordinates for array c
%% and copy pixels from b to their new locations in c
for row = 1:rows,
for col = 1:cols,
%% first compute the coords of the new point; note I'm rotating
%% and shifting to prevent any negative indices
%% got the 140 right-shift by trial & error
p = round([row col]*t) + [0 140];
%% now copy the current pixel value to the new matrix
c(p(1,1),p(1,2)) = b(row,col);
end
end
image(c);
hold on; % this holds the image window open so I can view one superimposed over the other
image(b);
imwrite(b,'tri.png');
imwrite(c,'newtri.png');
Images are attached. triangles.png is the original image. tri.png is just the red layer of that file; that's the array I'm rotating. newtri.png is the result.
Edit: I just noticed that tri.png got rotated somehow in the process of uploading, so it wasn't oriented the same as the original image. Now it's OK.
Edit: added more comments to the code (everything starting with % is a comment)
Attachments
Last edited: