Project 1
'''
The input image for this challenge can be found in the attachment section. Solve the following problem statements.
1.Script a function to perform image rotation by deriving the rotation matrix for a 140 degree rotation angle.
2.Now on the rotated image perform a scaling operation which reduces the size of the image by 50% of the original size.
3.Take the original image and perform cropping operation manually which focuses on the subject of the input image.
Deliverables:
1.The rotated image
2.The scaled image
3.Cropped image
4.Necessary calculations for the scaling operations which fixes the scaling percentage.
'''
import cv2
import numpy as np
def read_img(img_path):
image = cv2.imread(img_path)
return image
def display_img(image_window,image):
cv2.imshow(image_window,image)
cv2.waitKey(0)
def save_img(img_name,image):
cv2.imwrite(img_name,image)
1.Script a function to perform image rotation by deriving the rotation matrix for a 140 degree rotation angle.
# reading image
image =read_img('Challenge1.png')
# rotation function
def rotation_img(image,angle,scale):
height,width = image.shape[:2]
center = (width/2,height/2)
rotation_matrix = cv2.getRotationMatrix2D(center,145,1.0)
rotation_img = cv2.warpAffine(image,rotation_matrix,(width,height))
return rotation_img
# calling rotation function and saving image
rotated_img = rotation_img(image,145,1.0)
display_img('rotation_window',rotated_img)
save_img('Saved/rotated_img.png',rotated_img)
2.Now on the rotated image perform a scaling operation which reduces the size of the image by 50% of the original size.
# scaling operation on rotated image
def scale_img(image,scale_percent,method_num):
height = image.shape[0]
width = image.shape[1]
change_height = int((height * scale_percent/100))
change_width = int((width * scale_percent/100))
dimensions = (change_width,change_height)
method = [cv2.INTER_AREA,cv2.INTER_LINEAR,cv2.INTER_NEAREST,cv2.INTER_CUBIC,cv2.INTER_LANCZOS4]
scale_method = method[method_num]
scale_img = cv2.resize(image,dimensions,interpolation = scale_method)
return scale_img
# calling scaling function and saving image
scaled_img = scale_img(rotated_img,50,0)
cv2.imwrite('Saved/scaled_img1.png',scaled_img)
3.Take the original image and perform cropping operation manually which focuses on the subject of the input image.
# cropping function
def crop_img(image,dimensions):
h_s,h_e,w_s,w_e = dimensions
image_dimensions = image.shape
height_dimensions = [h_s,h_e]
width_dimensions = [w_s,w_e]
np.clip(height_dimensions,a_min=0,a_max =image_dimensions[0])
np.clip(width_dimensions,a_min=0,a_max =image_dimensions[1])
crop_img = image[height_dimensions[0]:height_dimensions[1],width_dimensions[0]:width_dimensions[1]]
return crop_img
# cropping image
crop_dimensions = [105,540,180,850]
cropped_image = crop_img(image,crop_dimensions)
display_img('cropped_image_window' , cropped_image)
save_img('Saved/cropped_image.png',cropped_image)