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:

  1. Import Libraries:

    • cv2 for OpenCV functions.
    • numpy for numerical operations.
  2. affine_transform Function:

    • Takes an image, source points (src_points), and destination points (dst_points) as input.
    • Calculates the transformation matrix (m) using cv2.getAffineTransform based 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.
  3. 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_transform function to perform the transformation.
    • Displays the transformed image using cv2.imshow.
    • Waits for a key press to close the windows using cv2.waitKey(0).

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.

Python OpenCV: Affine Transformation for Image Manipulation

原文地址: https://www.cveoy.top/t/topic/pe43 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录