基于python的图像变换(翻转、平移、缩放、旋转、仿射和透视变换)

翻转

在这里插入图片描述
在这里插入图片描述

import cv2
from matplotlib import pyplot as plt
image = cv2.imread("1.jpg")
#转换颜色通道
b, g, r = cv2.split(image)
image = cv2.merge([r, g, b])
#图像水平翻转
flipped1 = cv2.flip(image,1)
#图像垂直翻转
flipped2 = cv2.flip(image,0)
#图像水平垂直翻转
flipped3 = cv2.flip(image,-1)
#显示图像
plt.subplot(141),plt.imshow(image),plt.title('Input')
plt.xticks([]),plt.yticks([])
plt.subplot(142),plt.imshow(flipped1),plt.title('Output1')
plt.xticks([]),plt.yticks([])
plt.subplot(143),plt.imshow(flipped2),plt.title('Output2')
plt.xticks([]),plt.yticks([])
plt.subplot(144),plt.imshow(flipped3),plt.title('Output3')
plt.xticks([]),plt.yticks([])
plt.show()

平移


import cv2
import numpy as np

img = cv2.imread('1.jpg')
M = np.float32([[1, 0, 30], [0, 1, 50]])
res = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
while 1:
	# 显示图像
	cv2.imshow('img', img)
	cv2.imshow('res', res)
	k = cv2.waitKey(5) & 0xFF
	if k == 27:
		break
# 关闭窗口
cv2.destroyAllWindows()

旋转和缩放


import cv2
image = cv2.imread("1.jpg")
cv2.imshow("Original",image)
cv2.waitKey(0)
(h,w) = image.shape[:2]
center = (w / 2,h / 2)
#旋转45度,缩放0.75
M = cv2.getRotationMatrix2D(center,45,0.75)
rotated = cv2.warpAffine(image,M,(w,h))
cv2.imshow("Rotated by 45 Degrees",rotated)
cv2.waitKey(0)
#旋转-45度。缩放1.25
M = cv2.getRotationMatrix2D(center,-45,1.25)
rotated = cv2.warpAffine(image,M,(w,h))
cv2.imshow("Rotated by -90 Degrees",rotated)
cv2.waitKey(0)

在这里插入图片描述
在这里插入图片描述

仿射和透视变换矩阵

在这里插入图片描述

仿射

import cv2 as cv
from matplotlib import pyplot as plt
import numpy as np

img = cv.imread('1.jpg')
rows,cols,ch = img.shape
#指定对应变换点
pts1 = np.float32([[50,50],[200,50],[50,200]])
pts2 = np.float32([[10,100],[200,50],[100,250]])
#得到仿射矩阵
M = cv.getAffineTransform(pts1,pts2)
#实现仿射变换
dst = cv.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()

透视变换

import cv2 as cv
import numpy as np

image=cv.imread('1.jpg')
# 得到图片的高和宽
height,width=image.shape[:2]
# 定义对应的点
points1 = np.float32([[75,55], [340,55], [33,435], [400,433]])
points2 = np.float32([[0,0], [360,0], [0,420], [360,420]])
# 计算得到转换矩阵
M = cv.getPerspectiveTransform(points1, points2)
# 实现透视变换转换
processed = cv.warpPerspective(image,M,(360, 420))
cv.imshow('original',image)
cv.imshow('perspective', processed)
cv.waitKey(0)
cv.destroyAllWindows()

在这里插入图片描述
后续
如果想了解更多物联网、智能家居项目知识,可以关注我的项目实战专栏。
或者关注公众号。
在这里插入图片描述

编写不易,感谢支持。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

跋扈洋

编写不易,打赏支持一下我吧

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

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

打赏作者

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

抵扣说明:

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

余额充值