二、opencv中图像的几何变换-python版本(平移、缩放、旋转、仿射、透射)

1、图形的平移

import cv2 
import numpy as np
通过numpy来构造这个矩阵,并将其传给仿射函数cv2.warpAffine( )
img = cv2.imread('4.jpg')
#构造移动矩阵H
H = np.float32([[1, 0, 50], [0, 1, 25]])
rows, cols = img.shape[:2]
print(img.shape)
print(rows, cols)
res = cv2.warpAffine(img, H, (cols, rows))  # rows和cols需要反置。
cv2.imshow('origin_picture', img)
cv2.imshow('new_picture', res)
cv2.waitKey(0)

2、图像的放大和缩小
img = cv2.imread(‘4.jpg’)
(1)设置图像缩放比例来对图像进行放大、缩小
res1=cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
height, width = img.shape[:2]
(2)设置图像的大小,不需要缩放因子

res2 = cv2.resize(img, (int(0.8*width), int(0.8*height)), interpolation=cv2.INTER_AREA)
cv2.imshow('origin_picture', img)
cv2.imshow('res1', res1)
cv2.imshow('res2', res2)
cv2.waitKey(0)

3、图像的旋转
img = cv2.imread(‘4.jpg’)
rows, cols = img.shape[:2]
#第一个参数是旋转中心,第二个参数是旋转角度,第三个参数是缩放比例

M1 = cv2.getRotationMatrix2D((cols/2, rows/2), 45, 0.5)
M2 = cv2.getRotationMatrix2D((cols/2, rows/2), 45, 2)
M3 = cv2.getRotationMatrix2D((cols/2, rows/2), 45, 1)
res1 = cv2.warpAffine(img, M1, (cols, rows))
res2 = cv2.warpAffine(img, M2, (cols, rows))
res3 = cv2.warpAffine(img, M3, (cols, rows))
cv2.imshow('res1', res1)
cv2.imshow('res2', res2)
cv2.imshow('res3', res3)
cv2.waitKey(0)
cv2.destroyAllWindows()

4、图像的仿射

img = cv2.imread('4.jpg')
rows, cols = img.shape[:2]
pts1 = np.float32([[50, 50], [200, 50], [50, 200]])
pts2 = np.float32([[10, 100], [200, 50], [100, 250]])
#类似于构造矩阵
M = cv2.getAffineTransform(pts1, pts2)
res = cv2.warpAffine(img, M, (cols, rows))
cv2.imshow('原图', img)
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()

5、图像的透射

img = cv2.imread('4.jpg')
rows, cols = img.shape[:2]
pts1 = np.float32([[56, 65], [238, 52], [28, 237], [239, 240]])
pts2 = np.float32([[0, 0], [200, 0], [0, 200], [200, 200]])
M = cv2.getPerspectiveTransform(pts1, pts2)
res = cv2.warpPerspective(img, M, (cols, rows))
cv2.imshow('yuantu', img)
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小树苗m

您的打赏,是我的动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值