1)图像翻转
# 图像翻转示例
import numpy as np
import cv2
im = cv2.imread("../data/Linus.png")
cv2.imshow("src", im)
# 0-垂直镜像
im_flip0 = cv2.flip(im, 0)
cv2.imshow("im_flip0", im_flip0)
# 1-水平镜像
im_flip1 = cv2.flip(im, 1)
cv2.imshow("im_flip1", im_flip1)
cv2.waitKey()
cv2.destroyAllWindows()
执行结果:
2)图像仿射变换
# 图像仿射变换
import numpy as np
import cv2
def translate(img, x, y):
"""
坐标平移变换
:param img: 原始图像数据
:param x:平移的x坐标
:param y:平移的y坐标
:return:返回平移后的图像
"""
h, w = img.shape[:2] # 获取图像高、宽
# 定义平移矩阵
M = np.float32([[1, 0, x],
[0, 1, y]])
# 使用openCV仿射操作实现平移变换
shifted = cv2.warpAffine(img, M, (w, h)) # 第三个参数为输出图像尺寸
return shifted # 返回平移后的图像
def rotate(img, angle, center=None, scale=1.0):
"""
图像旋转变换
:param img: 原始图像数据
:param angle: 旋转角度
:param center: 旋转中心,如果为None则以原图中心为旋转中心
:param scale: 缩放比例,默认为1
:return: 返回旋转后的图像
"""
h, w = img.shape[:2] # 获取图像高、宽
# 旋转中心默认为图像中心
if center is None:
center = (w / 2, h / 2)
# 计算旋转矩阵
M = cv2.getRotationMatrix2D(center, angle, scale)
# 使用openCV仿射变换实现函数旋转
rotated = cv2.warpAffine(img, M, (w, h))
return rotated # 返回旋转后的矩阵
if __name__ == "__main__":
# 读取并显示原始图像
im = cv2.imread("../data/Linus.png")
cv2.imshow("SrcImg", im)
# 图像向下移动50像素
shifted = translate(im, 0, 50)
cv2.imshow("Shifted1", shifted)
# 图像向左移动40, 下移动40像素
shifted = translate(im, -40, 40)
cv2.imshow("Shifted2", shifted)
# 逆时针旋转45度
rotated = rotate(im, 45)
cv2