Tuesday 2 January 2024

Translation transformation in OpenCV

Translation is an affine transformation, that moves an object or image by a fixed distance along the x and y axes. Transformation matrix for this operation is defined like below.

 

[1 0 tx]

[0 1 ty]

 

Here, (tx, ty) represent the translation distances in the x and y directions. Using cv2.wrapAffine method and a translation matrix, we can shift the image toward x and y axis in OpenCV.

 

Example

def translate(img, x, y):
    translation_matrix = np.float32([[1, 0, x], [0, 1, y]])
    width = img.shape[1]
    height = img.shape[0]

    dimensions = (width, height)
    return cv.warpAffine(img, translation_matrix, dimensions)

 

a.   If x is positive, then it moves the image to Right

b.   If x is negative, then it moves the image to Left

c.    If y is positive, then it moves the image to Down

d.   If y is negative, then it moves the image to Up

 

Find the below working application.

 

translation.py

import cv2 as cv
import numpy as np

# x : Right
# -x : Left
# y : Down
# -y : Up
def translate(img, x, y):
    translation_matrix = np.float32([[1, 0, x], [0, 1, y]])
    width = img.shape[1]
    height = img.shape[0]

    dimensions = (width, height)
    return cv.warpAffine(img, translation_matrix, dimensions)

# Read the image as matrix of pixels
image = cv.imread('nature.png')
image = cv.resize(image, (1000, 800))

# Display the image in new window
cv.imshow('Nature', image)
cv.imshow('Image shifted 150 pixels right and 100 pixels down', translate(image, 150, 100))
cv.imshow('Image shifted 150 pixels left and 200 pixels up', translate(image, -150, -200))

# Wait for Infinite amount of time for a keyboard key to be pressed
cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

 

Output

 

Original image

 

 


Image shifted 150 pixels right and 100 pixels down

 


 

Image shifted 150 pixels left and 200 pixels up.



 

Previous                                                    Next                                                    Home

No comments:

Post a Comment