Python_opencv几何变换

# 几何变换
import cv2
import numpy as np
from matplotlib import pyplot as plt

def show(img):
    print("The current input image shape is", img.shape)
    cv2.imshow("images", img)
    cv2.waitKey()
    cv2.destroyAllWindows()
# BGR 2 RGB
img = cv2.imread("girl.jpg", 1)[...,::-1]
h, w, c = img.shape
print(h, w, c)
# 平移
# 平移变换矩阵 形式--->[[1, 0, tx], [0, 1, ty]]
# 数据转为np.float32类型
M = np.float32([[1,0,100],[0,1,50]])
dst = cv2.warpAffine(img, M, (w,h))  # 平移矩阵 (源图, 变换矩阵, 输出图像大小)
# show(dst)

# 旋转变换
# getRotationMatrix2D --> (旋转点,旋转角度, 缩放比例)
M = cv2.getRotationMatrix2D((w/3, h/3), 45, 0.4)
dst = cv2.warpAffine(img, M, (w, h))
# show(dst)

# 仿射变换
# 仿射变换是一种二维坐标到二维坐标之间的线性变换,并保持二维图形的“平直性”。转换前平行的线,在转换后依然平行
# 需要提供原图像中三个点以及他们在输出图像中的位置
pts1 = 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, (w, h))

# plt.subplot(121), plt.imshow(img), plt.title("Input")
# plt.subplot(122), plt.imshow(dst), plt.title("Output")
# plt.show()

# 透视变换
# 需要在原图上找到4个点,以及他们在输出图上对应的位置,这四个点中任意三个都不能共线
pts1 = 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,(w, h))

plt.subplot(121), plt.imshow(img), plt.title("Input")
plt.subplot(122), plt.imshow(dst), plt.title("Output")
plt.show()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值