基础知识
仿射变换:平移,镜像(水平、垂直),旋转
图像的算数运算:
图像的腐蚀和膨胀:
开运算的应用举例
1.图像翻转
# 08_flip.py
# 图像翻转
import cv2
im = cv2.imread("../data/Linus.png")
cv2.imshow("im", 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.图像位置变换
# 09_affine.py
# 图像仿射变换(旋转、平移)
import numpy as np
import cv2
def translate(im, x, y):
"""
对图像进行平移变换
:param im: 原始图像数据
:param x: 水平方向平移的像素
:param y: 垂直方向平移的像素
:return: 返回平移后的图像数据
"""
h, w = im.shape[:2] # 取出原图像高度、宽度
# 定义平移矩阵
M = np.float32([[1, 0, x],
[0, 1, y]])
# 调用warpAffine函数实现平移变换
shifted = cv2.warpAffine(im, # 原始图像
M, # 平移矩阵
(w, h)) # 输出图像大小
return shifted
def rotate(im, angle, center=None, scale=1.0):
"""
图像旋转变换
:param im: 原始图像
:param angle: 旋转角度
:param center: 旋转中心
:param scale: 缩放比例
:return: 返回经过旋转后的图像
"""
h, w = im.shape[:2] # 获取图像高度、宽度
# 计算旋转中心
if center is None:
center = (w / 2, h / 2)
# 生成旋转矩阵
M = cv2.getRotationMatrix2D(center, angle, scale)
# 调用warpAffine函数实现旋转变换
rotated = cv2.warpAffine(im, M, (w, h))
return rotated
if __name__ == "__main__":
# 读取原始图像
im = cv2.imread("../data/Linus.png")
cv2.imshow("im", im)
# 向下移动50像素
shifted = translate(im, 0, 50)
cv2.imshow("shifted_1", shifted)
# 向左移动40像素,向下移动50像素
shifted = translate(im, -40, 50)
cv2.imshow("shifted_2", shifted)
# 逆时针旋转45度
rotated = rotate(im, 45)
cv2.imshow("rotated_1", rotated)
# 顺时针旋转90度
rotated = rotate(im, -90)
cv2.imshow("rotated_2", rotated)
cv2.waitKey() # 等待用户按某个按键
cv2.destroyAllWindows() # 销毁所有创建的窗口