To perform image transformation such as Translation, Scaling, Shearing, Reflection, Rotation and Cropping using OpenCV and Python.
Anaconda - Python 3.7
Import the required libraries.
Read the image and convert the image from RGB to BGR.
Perform the following Image translations
- Image Translation
- Image Scaling
- Image Shearing
- Image Reflection
- Image Rotation
- Image Cropping
Developed By: Y SHAVEDHA
Register Number: 212221230095
i)Image Translation
#Translation
image = cv2.imread('img.jpg')
#convert BGR TO RGB
image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
# Disable x and y axis
plt.axis('off')
#show the image
plt.imshow(image)
plt.show()
#get the image shape
rows,cols,dim = image.shape
#Transformation matrix for translation
M = np.float32([[1,0,60],
[0,1,80],
[0,0,1]])
# Apply a perspective transformation to the image
translated_image = cv2.warpPerspective(image,M,(cols,rows))
#Disable x,y axis
plt.axis('off')
#show the resulting image
plt.imshow(translated_image)
plt.show()
ii) Image Scaling
#Scaling the image
plt.axis('off')
#show the original image
plt.imshow(image)
plt.show()
M = np.float32([[1.5,0,0],
[0,1.8,0],
[0,0,1]])
scaled_image = cv2.warpPerspective(image,M,(cols*2,rows*2))
plt.axis('off')
plt.imshow(scaled_image)
plt.show()
iii)Image shearing
# Shearing
#shearing applied to x axis
M_x = np.float32([[1,0.5,0],
[0,1,0],
[0,0,1]])
#Shearing applied to y-axis
M_y = np.float32([[1,0,0],
[0.5,1,0],
[0,0,1]])
sheared_img_xaxis = cv2.warpPerspective(image,M_x,(int(cols*1.5),int(rows*1.5)))
sheared_img_yaxis = cv2.warpPerspective(image,M_y,(int(cols*1.5),int(rows*1.5)))
plt.axis('off')
plt.imshow(sheared_img_xaxis)
plt.show()
plt.axis('off')
plt.imshow(sheared_img_yaxis)
plt.show()
iv)Image Reflection
#Reflection
#Transformation matrix for x_axis
M_x = np.float32([[1,0,0],
[0,-1,rows],
[0,0,1]])
#Transformation matrix for y_axis
M_y = np.float32([[-1,0,cols],
[0,1,0],
[0,0,1]])
ref_xaxis = cv2.warpPerspective(image,M_x,(int(cols),int(rows)))
ref_yaxis = cv2.warpPerspective(image,M_y,(int(cols),int(rows)))
plt.axis('off')
plt.imshow(ref_xaxis)
plt.show()
plt.axis('off')
plt.imshow(ref_yaxis)
plt.show()
v)Image Rotation
#Rotation
#Angle from degree to radian
angle = np.radians(10)
#Transform matrix for rotation
M = np.float32([[np.cos(angle),-(np.sin(angle)),0],
[np.sin(angle),np.cos(angle),0],
[0,0,1]])
rotated_img = cv2.warpPerspective(image,M,(int(cols),int(rows)))
plt.axis('off')
plt.imshow(rotated_img)
plt.show()
vi)Image Cropping
#cropping
#get 200 pixels from 100 to 300 on both x and y axis
cropped_img = image[100:300,100:300]
plt.axis('off')
plt.imshow(cropped_img)
plt.show()
Thus the different image transformations such as Translation, Scaling, Shearing, Reflection, Rotation and Cropping are done using OpenCV and python programming.