ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-03-09 13:59:26  阅读:260  来源: 互联网

标签:img 缩放 08 50 cols destroyAllWindows waitKey cv 仿射变换


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有