python opencv图像几何变换

图片缩放:

import cv2

img = cv2.imread('LightHouse.jpg')
height, width = img.shape[:2]
res = cv2.resize(img, (int(0.5*width),int(0.5*height)),interpolation= cv2.INTER_CUBIC)
cv2.imshow('image', res)
cv2.waitKey(0)
cv2.destroyAllWindows()

图像平移

import numpy as np
import cv2

img = cv2.imread('LightHouse.jpg')
rows,cols = img.shape[:2]
M =np.float32([[1,0,20],[0,1,50]])
#向水平方向平移20,向垂直方向平移50
res = cv2.warpAffine(img,M,(cols, rows))
cv2.imshow('image', res)
cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述
图像旋转

import cv2
img = cv2.imread('LightHouse.jpg')
rows,cols = img.shape[:2]
M = cv2.getRotationMatrix2D((cols*0.5, rows*0.5),45,1)
'''
参数1 必选参数。用于设置旋转中心点,点坐标为OpenCV图像坐标系下的坐标。
参数2 必选参数。用于设置旋转的角度,单位为度。
参数3 必选参数。用于设置缩放系数,即对旋转的图像进行缩放。
'''
res = cv2.warpAffine(img,M,(cols, rows))
cv2.imshow('image', res)
cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述
图片仿射变换:
用于侵写照片修正,
在仿射变换中,原始图像中的所有平行线在输出图像中仍将平行。为了找到变换矩阵,我们需要
输入图像中的三个点及其在输出图像中的对应位置。

import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('badlighthouse.jpg')
rows,cols = img.shape[:2]
pts1 = np.float32([[0,0],[0,rows],[cols,0]])
pts2 = np.float32([[0,rows],[cols,rows],[0,0]])
M = cv2.getAffineTransform(pts1,pts2)
res = cv2.warpAffine(img,M,(cols,rows))
plt.subplot(121)
plt.imshow(img)
plt.title('input')
plt.subplot(122),plt.imshow(res),plt.title('output')
plt.show()

在这里插入图片描述
透视变换
对于透视变换,您需要3x3变换矩阵。即使在转换后,直线也将保持直线。要找到此变换矩阵,您需要在输入图像上有4个点,在输出图像上需要相应的点。在这四个点中,其中三个不应共线。
透视变换也用来修正照片,但是相比仿射变换的旋转倾斜修正,透视变换更倾向于视角方面导致图片倾斜的修正问题:

import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('src.jpg')
rows,cols = img.shape[:2]
pts1 = np.float32([[275,209],[507,281],[184,463],[434,547]])
pts2 = np.float32([[90,360],[333,360],[100,612],[373,612]])
M = cv2.getPerspectiveTransform(pts1, pts2)
res = cv2.warpPerspective(img,M,(cols,rows))
plt.subplot(121)
plt.imshow(img)
plt.title('input')
plt.subplot(122),plt.imshow(res),plt.title('output')
plt.show()

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值