cv2小记——几何变换
发布日期:2021-06-30 15:01:24 浏览次数:2 分类:技术文章

本文共 2529 字,大约阅读时间需要 8 分钟。

# coding: utf-8# !/usr/bin/python"""@File       :   几何变换.py@Author     :   jiaming@Modify Time:   2020/1/31 15:51@Contact    :   https://blog.csdn.net/weixin_39541632@Version    :   1.0@Desciption :   几何变换                对图像进行各种几何变换:移动、旋转、仿射变换                cv2.getPerspectiveTransform()"""import osimport sysimport numpy as npimport cv2import pprintfrom matplotlib import pyplot as pltrawPath = os.path.abspath(__file__)currentFile = os.path.basename(sys.argv[0])dataPath = rawPath[:rawPath.find(currentFile)] + r'static\\'"""OpenCV 提供了两个变换函数,cv2.warpAffine(martix(2x3),) 和 cv2.warpPerspective(martix(3x3),)"""

扩展缩放

"""扩展缩放:改变图像大小。OpenCV提供的函数 cv2.resize 可以实现这个功能 插值方法推荐: cv2.INTER_CUBIC 和cv2.INTER_LINEAR对shrinking:cv2.INTER_AREA该方法可以避免波纹的出现对zooming:优选的interpolation方法:cv2.INTER_CUBIC和cv2.INTER_LINEAR(默认)None: 图像输出尺寸,但是后面设置了缩放因子res = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)res = cv2.resize(img, (width, leight), interpolation=cv2.INTER_CUBIC)"""

平移

在这里插入图片描述

""""平移:构建移动矩阵将参数传给 cv2.warpAffine()"""img = cv2.imread('xxx')rows, cols = img.shapeM = np.float32([[1, 0, 100], [0, 1, 50]])  # 类型是 np.float32 移动步幅:(100, 50)dst = cv2.warpAffine(img, M, (cols, rows))  # 第三个参数是输出图像大小 (宽,高)cv2.imshow('dst', dst)cv2.waitKey(0)cv2.destroyAllWindows()

旋转

在这里插入图片描述

"""旋转:cv.getRotationMatrix"""img = cv2.imread('xxx')rows, cols = img.shape# 第一个参数是旋转中心# 第二个为旋转角度# 第三个为旋转后的缩放因子M = cv2.getRotationMatrix2D(((cols - 1) / 2.0, (rows - 1) / 2.0), 90, 1)# 第三个参数是输出图像的尺寸中心dst = cv2.warpAffine(img, M, (cols, rows))cv2.imshow('dst', dst)cv2.waitKey(0)cv2.destroyAllWindows()

仿射变换

"""仿射变换:原图中所有的平行线在结果图像中同样平行cv2.getAffineTransform """img = cv2.imread('xxx')rows, cols, ch = img.shapepts1 = np.float32([[50, 50], [200, 50], [50, 200]])pts2 = np.float32([[10, 100], [200, 50], [100, 250]])M = cv2.getAffineTransform(pts1, pts2)dst = cv2.warpAffine(img, M, (cols, rows))plt.subplot(121), plt.imshow(img), plt.title('Input')plt.subplot(122), plt.imshow(dst), plt.title('Output')plt.show()

透视变换

"""透视变换:对于透视变换,需要一个3x3变换矩阵。 即使在转换之后,直线仍将保持笔直. 要找到此变换矩阵,输入图像上需要4个点,输出图像上需要相应的点. 在这4个点中,其中3个不应该共线. 然后可以通过函数cv2.getPerspectiveTransform找到变换矩阵. 然后将cv2.warpPerspective应用于此3x3变换矩阵。"""img = cv2.imread('xxx')rows, cols, ch = img.shapepts1 = np.float32([[56, 65], [368, 52], [28, 387], [389, 390]])pts2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])M = cv2.getPerspectiveTransform(pts1, pts2)dst = cv2.warpPerspective(img, M, (300, 300))plt.subplot(121), plt.imshow(img), plt.title('Input')plt.subplot(122), plt.imshow(dst), plt.title('Output')plt.show()

转载地址:https://jiaming.blog.csdn.net/article/details/104125098 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:第二章:函数(Ⅳ)
下一篇:cv2小记——颜色空间转换

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月15日 06时17分40秒