Python OpenCV: Affine Transformation for Image Manipulation
import cv2
import numpy as np
def affine_transform(image, src_points, dst_points):
height, width = image.shape[:2]
dsize = (width, height)
src = np.float32(src_points)
dst = np.float32(dst_points)
m = cv2.getAffineTransform(src, dst)
transformed_image = cv2.warpAffine(image, m, dsize)
return transformed_image
if __name__ == "__main__":
img = cv2.imread('bee.jpg')
cv2.imshow('img', img)
src_points = [[0, 0], [img.shape[1] - 10, 0], [0, img.shape[0] - 1]]
dst_points = [[50, 50], [img.shape[1] - 100, 80], [100, img.shape[0] - 100]]
transformed_img = affine_transform(img, src_points, dst_points)
cv2.imshow('imgThreePoint', transformed_img)
cv2.waitKey(0)
This code demonstrates how to apply an affine transformation to an image using OpenCV and Python. Here's a breakdown:
-
Import Libraries:
cv2for OpenCV functions.numpyfor numerical operations.
-
affine_transformFunction:- Takes an image, source points (
src_points), and destination points (dst_points) as input. - Calculates the transformation matrix (
m) usingcv2.getAffineTransformbased on the source and destination points. - Performs the affine transformation using
cv2.warpAffine, applying the matrix to the image and specifying the output image size. - Returns the transformed image.
- Takes an image, source points (
-
Main Execution Block (
if __name__ == "__main__"):- Loads the image (
bee.jpg). - Displays the original image using
cv2.imshow. - Defines the source points (
src_points) on the original image and the corresponding destination points (dst_points) where you want them to be mapped in the transformed image. - Calls the
affine_transformfunction to perform the transformation. - Displays the transformed image using
cv2.imshow. - Waits for a key press to close the windows using
cv2.waitKey(0).
- Loads the image (
By specifying three points and their corresponding destinations, you can create visually interesting effects like shearing, rotation, and scaling of the image. This technique is useful for various image processing tasks.
原文地址: https://www.cveoy.top/t/topic/pe43 著作权归作者所有。请勿转载和采集!