How to perform matrix transformation in OpenCV Python?


The cv2.transform() function performs the matrix transformation of each element of the input array. We could apply this transformation directly on the image as the images are NumPy ndarrays in OpenCV. To use this function, we should first define a transformation matrix m. The number of channels in the output will be the same as the number of rows in the transformation matrix m.

Steps

To find matrix transform of an input image, you could follow the steps given below-

  • Import the required libraries OpenCV and NumPy. Make sure you have already installed them.

  • Read the input image using cv2.imread() method. Specify the full path of the image.

  • Define a transformation matrix m of size (3,3). You can generate the transformation matrix as the random numbers or define a custom matrix.

  • Find the matrix transform of the image using cv2.transform(). Pass the transformation matrix m to the cv2.transform() function as a parameter.

  • Display the transformed image.

Let's look at the examples below to perform the matrix transformation on an input image.

Input Image

We will use the following image as the input file in the example below.


Example

In this example, we find matrix transformation of an input image. We define a transformation matrix as a 3×3 matrix of random numbers.

# import required libraries import cv2 import numpy as np # read input image img = cv2.imread('leaf1.jpg') # define transformation matrix m = np.random.randn(3,3) # apply the cv2.transform to perform matrix transformation img_tr = cv2.transform(img, m, None) # display the transformed image cv2.imshow("Transformed Image", img_tr) cv2.waitKey(0) cv2.destroyAllWindows()

Output

On execution of the above code, it will produce the following output window −


Note − You may get the output image with different colors and brightness as the transformation matrix is generated using random numbers.

Example

In this example, we find matrix transformation of an input image. We define a transformation matrix as a 3×3 matrix of ones.

# import required libraries import cv2 import numpy as np # read input image img = cv2.imread('leaf1.jpg') # define transformation matrix m = np.ones((3,3)) # apply the cv2.transform to perform matrix transformation img_tr = cv2.transform(img, m, None) # display the transformed image cv2.imshow("Transformed Image", img_tr) cv2.waitKey(0) cv2.destroyAllWindows()

Output

On execution of the above code, it will produce the following output window −


Updated on: 05-Dec-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements