• 掌握图像的缩放,平移,旋转等
1 图像缩放
API
cv2.resize(src,dsize,fx=0,fy=0,interpolation=cv2.INTER_LINEAR)
参数:
• src : 输入图像
• dsize: 绝对尺寸,直接指定调整后图像的大小
• fx,fy: 相对尺寸,将dsize设置为None,然后将fx和fy设置为比例因子即可
• interpolation:插值方法,
代码
import cv2 as cv
import matplotlib.pyplot as plt
# 1. 读取图片
img1 = cv.imread("opencv_learn\\sky.png")
# 2.图像缩放
# 2.1 绝对尺寸
rows,cols = img1.shape[:2]
res = cv.resize(img1,(2*cols,2*rows),interpolation=cv.INTER_CUBIC)
#w h
# 2.2 相对尺寸
res1 = cv.resize(img1,None,fx=0.5,fy=0.5)
# 3.2 使用matplotlib显示图像
fig,axes=plt.subplots(nrows=1,ncols=3,figsize=(10,8),dpi=100)
axes[0].imshow(res[:,:,::-1])
axes[0].set_title("绝对尺度(放大)")
axes[1].imshow(img1[:,:,::-1])
axes[1].set_title("原图")
axes[2].imshow(res1[:,:,::-1])
axes[2].set_title("相对尺度(缩小)")
plt.show()
2 平移
图像平移
图像平移将图像按照指定方向和距离,移动到相应的位置。
1. API
cv.warpAffine(img,M,dsize)
参数:
需求是将图像的像素点移动(50,100)的距离:
代码
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
# 1. 读取图像
img1 = cv.imread(“./image/image2.jpg”)
# 2. 图像平移
rows,cols = img1.shape[:2]
x坐标移动, y坐标移动
M = np.float32([[1,0,100],[0,1,50]])# 平移矩阵
dst = cv.warpAffine(img1,M,(cols,rows))
# 3. 图像显示
fig,axes=plt.subplots(nrows=1,ncols=2,figsize=(10,8),dpi=100)
axes[0].imshow(img1[:,:,::-1])
axes[0].set_title("原图")
axes[1].imshow(dst[:,:,::-1])
axes[1].set_title("平移后结果")
plt.show()
3 图像旋转
a. API
cv2.getRotationMatrix2D(center, angle, scale)
参数:
§ center:旋转中心
§ angle:旋转角度
§ scale:缩放比例
返回:
§ M:旋转矩阵
调用cv.warpAffine完成图像的旋转
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
# 1 读取图像
img = cv.imread("opencv_learn\\sky.png")
# 2 图像旋转
rows,cols = img.shape[:2]
# 2.1 生成旋转矩阵 旋转中心点坐标 角度 缩放比例
M = cv.getRotationMatrix2D((cols/2,rows/2),90,1)
# 2.2 进行旋转变换
dst = cv.warpAffine(img,M,(cols,rows))
# 3 图像展示
fig,axes=plt.subplots(nrows=1,ncols=2,figsize=(10,8),dpi=100)
axes[0].imshow(img[:,:,::-1])
axes[0].set_title("原图")
axes[1].imshow(dst[:,:,::-1])
axes[1].set_title("旋转后结果")
plt.show()
4 镜像翻转
img1 = cv2.flip(img,1) #镜像
'''
参数2 必选参数。用于指定镜像翻转的类型,
0表示绕×轴正直翻转,即垂直镜像翻转;
1表示绕y轴翻转,即水平镜像翻转;
-1表示绕×轴、y轴两个轴翻转,即对角镜像翻转。
参数3 可选参数。用于设置输出数组,即镜像翻转后的图像数据,默认为与输入图像数组大小和类型都相同的数组。
‘’’