You are on page 1of 2

Assignment 01

Question 01:
Write a program in your preferred programming language to rotate an image by some
random angle between 0 to 270 You can take greyscale image or color image.

Code:
% @U20EC050 NARENDRA GAVLI
clc;
clear;
close all;

% Load the image to be rotated


img = imread('./img/shree-bhagwat-geeta.jpg');

% Specify the rotation angle in degrees


rot_angle = input("Enter the angle you need for the rotating image :");

% Convert the rotation angle from degrees to radians


theta = deg2rad(rot_angle);

% Compute the size of the rotated image


[nrows, ncols, ~] = size(img);
new_size = ceil(sqrt(nrows^2 + ncols^2));

% Create an empty image with the new size


rot_img = uint8(zeros(new_size, new_size, 3));

% Compute the center of the image


cx = ceil(new_size/2);
cy = ceil(new_size/2);

% Compute the rotation matrix


R = [cos(theta) -sin(theta); sin(theta) cos(theta)];

% Loop over every pixel in the rotated image


for i = 1:new_size
for j = 1:new_size

% Compute the corresponding pixel location in the original image


x = i - cx;
y = j - cy;
p = R*[x; y];
p(1) = round(p(1) + cx);
p(2) = round(p(2) + cy);

% Check if the pixel location is inside the original image


if (p(1) >= 1 && p(1) <= nrows && p(2) >= 1 && p(2) <= ncols)

U20EC050 1|Page
% Copy the pixel value from the original image to the rotated
image
rot_img(i,j,:) = img(p(1),p(2),:);

end

end
end

% Display the original and rotated images side by side


figure;
subplot(1,2,1), imshow(img), title('Original Image');
subplot(1,2,2), imshow(rot_img), title(sprintf('Rotated Image by %d
degree',rot_angle));

Output:

U20EC050 2|Page

You might also like