树莓派学习笔记(五):树莓派上Python写OpenCV——形态变换

基础知识

在这里插入图片描述
仿射变换:平移,镜像(水平、垂直),旋转
在这里插入图片描述
图像的算数运算:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
图像的腐蚀和膨胀:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
开运算的应用举例
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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()  # 销毁所有创建的窗口

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值