How to do image translation in Open CV

share link

by vinitha@openweaver.com dot icon Updated: Sep 19, 2023

technology logo
technology logo

Solution Kit Solution Kit  

Image processing moves image pixels in a certain direction and distance. This basic operation creates various visual effects. It performs data augmentation for machine learning tasks. 


OpenCV, a popular computer vision library, provides functions to perform image translation easily. Here are the basic steps to perform OpenCV Image translation:  

  • Import OpenCV python.  
  • Read an image.  
  • Define the translation matrix.  
  • Perform the translation.  
  • Display or save the translated image.  


It encompasses various techniques for shifting an image's pixel coordinates differently. Here are some of the different types of image transformation:  

  • Horizontal and Vertical Translation  
  • Affine Transformation  
  • Image Warping  
  • Panning and Zooming  


Image translation is a versatile technique used in various fields and applications. Here are some examples of how people have used image translation. 

  • Face recognition and Emotion Detection  
  • Data Augmentation in Deep Learning  
  • Image Stitching for Panoramas  
  • Image Registration in Medical Imaging  


In conclusion, image translation is a fundamental technique in computer vision. You can change images by shifting their pixel values in different ways. You can use it in many areas to help achieve specific goals and effects.  

Fig: Preview of the output that you will get on running this code from your IDE

Code

In this solution we are using open cv library

 T0 = np.vstack((M0, np.array([0, 0, 1])))
 T1 = np.vstack((M1, np.array([0, 0, 1])))

 T = T1 @ T0

 M = T[0:2, :]

import numpy as np
import cv2

def get_rotation_mat(image, angle):
    w, h = (image.shape[1], image.shape[0])
    cx, cy = (w//2,h//2)

    M = cv2.getRotationMatrix2D((cx, cy), -1*angle, 1.0)
    #rotated = cv2.warpAffine(image, M, (w,h))
    return M

def get_translation_mat(d_x, d_y):
    M = np.float64([
        [1, 0, d_x],
        [0, 1, d_y]
    ])
    
    #return cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
    return M

def chain_affine_transformation_mats(M0, M1):
    """ 
    Chaining affine transformations given by M0 and M1 matrices.
    M0 - 2x3 matrix applying the first affine transformation (e.g rotation).
    M1 - 2x3 matrix applying the second affine transformation (e.g translation).
    The method returns M - 2x3 matrix that chains the two transformations M0 and M1 (e.g rotation then translation in a single matrix).
    """
    T0 = np.vstack((M0, np.array([0, 0, 1])))  # Add row [0, 0, 1] to the bottom of M0 ([0, 0, 1] applies last row of eye matrix), T0 is 3x3 matrix.
    T1 = np.vstack((M1, np.array([0, 0, 1])))  # Add row [0, 0, 1] to the bottom of M1.
    T = T1 @ T0  # Chain transformations T0 and T1 using matrix multiplication.
    M = T[0:2, :]  # Remove the last row from T (the last row of affine transformations is always [0, 0, 1] and OpenCV conversion is omitting the last row).
    return M

path = "dog.jpg"
image = cv2.imread(path)
angle = 30.0
d_x = 200
d_y = 300
#rotated = rotate_image(image, angle)
#translated = translate_image(rotated, d_x, d_y)
rotationM = get_rotation_mat(image, angle)  # Compute rotation transformation matrix
translationM = get_translation_mat(d_x, d_y)  # Compute translation transformation matrix

M = chain_affine_transformation_mats(rotationM, translationM)  # Chain rotation and translation transformations (translation after rotation)

transformed_image = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))  # Apply affine transformation with the chained (unified) matrix M.

cv2.imwrite("transformed_dog.jpg", transformed_image)  # Store output for testing

Instructions


Follow the steps carefully to get the output easily.


  1. Download and Install the PyCharm Community Edition on your computer.
  2. Open the terminal and install the required libraries with the following commands.
  3. Install open cv - pip install open cv
  4. Create a new Python file on your IDE.
  5. Copy the snippet using the 'copy' button and paste it into your python file.
  6. Run the current file to generate the output.


I hope you found this useful.


I found this code snippet by searching for ' How to rotate and translate an image with opencv ' in Kandi. You can try any such use case!

Environment tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. PyCharm Community Edition 2023.1
  2. The solution is created in Python 3.11.1 Version
  3. PCV 0.2.1 Version



Using this solution, we can able to do image translation in Open CV with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to do image translation in Open CV .

Dependency library

PCVby jesolem

Python doticonstar image 1881 doticonVersion:Currentdoticon
License: Permissive (BSD-2-Clause)

Open source Python module for computer vision

Support
    Quality
      Security
        License
          Reuse

            PCVby jesolem

            Python doticon star image 1881 doticonVersion:Currentdoticon License: Permissive (BSD-2-Clause)

            Open source Python module for computer vision
            Support
              Quality
                Security
                  License
                    Reuse

                      You can search for any dependent library on kandi like ' PCV '.

                      FAQ:  

                      1. What can you do with Open CV Image Translation, and how does it work?  

                      In OpenCV, image translation means moving the pixels of an image in a certain direction by a set distance.   

                      How to Use OpenCV Image Translation:  

                      • Import OpenCV  
                      • Read an Image  
                      • Define the Translation Matrix  
                      • Perform the Translation  
                      • Display or Save the Translated Image  


                      2. How does an affine transformation matrix help with image translation?  

                      An affine transformation matrix is a mathematical representation. It helps with image translation in computer vision and image processing. Here's how an affine transformation matrix aids in image translation:  

                      • Translation Component  
                      • Translation Parameters (tx and ty)  
                      • Affine Composition  
                      • Effect on Image Translation  


                      3. How do basic geometric transformations work in OpenCV Python?  

                      Basic geometric transformations in OpenCV Python involve operations and shearing to manipulate images. These transformations are typically achieved using transformation matrices. Here's an overview of how basic geometric transformations work in OpenCV Python:  

                      • Import OpenCV  
                      • Read an Image  
                      • Define Transformation Matrix  
                      • Apply the Transformation  
                      • Display or Save the Transformed Image  
                      • Cleanup  


                      4. Which techniques does OpenCV use for image rotation?  

                      In OpenCV, you can perform image rotation using various techniques and functions. Here are some commonly used techniques for image rotation in OpenCV:  

                      • cv2.getRotationMatrix2D()  
                      • cv2.getAffineTransform()  
                      • cv2.warpAffine() with Manual Transformation Matrix  


                      5. How can I access the data within a translated image using OpenCV Python?  

                      In Python, you can use OpenCV to access data in a translated image by indexing pixel values in the image array. OpenCV uses NumPy arrays to represent images.  

                      Support

                      1. For any support on kandi solution kits, please use the chat
                      2. For further learning resources, visit the Open Weaver Community learning page

                      See similar Kits and Libraries