其他分享
首页 > 其他分享> > opencv 缩放、平移、旋转、仿射变换和透视变换-08

opencv 缩放、平移、旋转、仿射变换和透视变换-08

作者:互联网

1.效果图

     

       

2. 代码 

import numpy as np
import cv2 as cv

"""
https://docs.opencv.org/master/da/d6e/tutorial_py_geometric_transformations.html
"""

img = cv.imread('C:/Users/Administrator/Desktop/messi.png', cv.IMREAD_GRAYSCALE)
rows, cols = img.shape

# (1) scaling
scaled_img1 = cv.resize(img, None, fx=2, fy=2, interpolation=cv.INTER_CUBIC)
# OR
height, width = img.shape[:2]
scaled_img2 = cv.resize(img, (2 * width, 2 * height), interpolation=cv.INTER_CUBIC)

# (2) translation. x方向移动100, y方向移动50
# cv.warpAffine:  2x3 transformation matrix
M = np.float32([[1, 0, 100], [0, 1, 50]])
translated_img = cv.warpAffine(img, M, (cols, rows))

# (3) rotate
# cols-1 and rows-1 are the coordinate limits.
M = cv.getRotationMatrix2D(center=((cols - 1) / 2.0, (rows - 1) / 2.0), angle=45, scale=1)
rotated_img = cv.warpAffine(img, M, (cols, rows))

# (4) affine transformation
"""
https://blog.csdn.net/Caesar6666/article/details/104158047
仿射变换的原则是原图上是直线,变换后也是直线,仿射 = 旋转 + 平移
为了找到2x3变换矩阵,需要原图的3个点和变换后的3个点;
cv.warpAffine
"""
pts1 = np.float32([[50, 50], [200, 50], [50, 200]])
pts2 = np.float32([[10, 100], [200, 50], [100, 250]])
M = cv.getAffineTransform(src=pts1, dst=pts2)
affine_img = cv.warpAffine(img, M, dsize=(cols, rows))

# (5) perspective transformation
"""
透视变换把一个二维坐标系转换为三维坐标系,然后把三维坐标系投影到新的二维坐标系。
变换后,直线依然是直线。一个平行四边形,经过仿射变换后依然是平行四边形;而经过透视变换后只是一个四边形(不再平行了);
为了找到3x3变换矩阵,需要原图的4个点和变换后的4个点;
cv.getPerspectiveTransform
"""
pts1 = np.float32([[56, 65], [368, 52], [28, 387], [389, 390]])
pts2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])
M = cv.getPerspectiveTransform(src=pts1, dst=pts2)
perspective_img = cv.warpPerspective(img, M, dsize=(300, 300))


cv.imshow('translated_img', translated_img), cv.waitKey(0), cv.destroyAllWindows()
cv.imshow('scaled_img1', scaled_img1), cv.waitKey(0), cv.destroyAllWindows()
cv.imshow('scaled_img2', scaled_img2), cv.waitKey(0), cv.destroyAllWindows()
cv.imshow('rotated_img', rotated_img), cv.waitKey(0), cv.destroyAllWindows()
cv.imshow('affine_img', affine_img), cv.waitKey(0), cv.destroyAllWindows()
cv.imshow('perspective_img', perspective_img), cv.waitKey(0), cv.destroyAllWindows()

 

标签:img,缩放,08,50,cols,destroyAllWindows,waitKey,cv,仿射变换
来源: https://blog.csdn.net/jizhidexiaoming/article/details/114580915