python-OpenCV旋转操作黑边的去除

python-OpenCV图像旋转操作

使用getRotationMatrix生成仿射变换矩阵,然后使用warpAffine进行压缩和显示。

import cv2
import numpy as np

# 本人的图片路径,导入图片
imgPath = "D:/pycharm/myfile/tensorflow_application/lena.jpg"
img = cv2.imread(imgPath)
cv2.imshow("test0", img)

这里写图片描述

# 进行旋转操作
w, h, depth = img.shape
img_change = cv2.getRotationMatrix2D((w / 2, h / 2), 45, 1)
res = cv2.warpAffine(img, img_change, (w, h))
cv2.imshow("test1", res)

这里写图片描述

去除黑边操作

# 去除黑边的操作
crop_image = lambda img, x0, y0, w, h: img[x0:x0+w, y0+h]  # 定义裁切函数,后续裁切黑边使用


def rotate_image(img, angle, crop):
    """
    angle: 旋转的角度
    crop: 是否需要进行裁剪,布尔向量
    """
    w, h = img.shape[:2]
    # 旋转角度的周期是360°
    angle %= 360
    # 计算仿射变换矩阵
    M_rotation = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1)
    # 得到旋转后的图像
    img_rotated = cv2.warpAffine(img, M_rotation, (w, h))

    # 如果需要去除黑边
    if crop:
        # 裁剪角度的等效周期是180°
        angle_crop = angle % 180
        if angle > 90:
            angle_crop = 180 - angle_crop
        # 转化角度为弧度
        theta = angle_crop * np.pi / 180
        # 计算高宽比
        hw_ratio = float(h) / float(w)
        # 计算裁剪边长系数的分子项
        tan_theta = np.tan(theta)
        numerator = np.cos(theta) + np.sin(theta) * np.tan(theta)

        # 计算分母中和高宽比相关的项
        r = hw_ratio if h > w else 1 / hw_ratio
        # 计算分母项
        denominator = r * tan_theta + 1
        # 最终的边长系数
        crop_mult = numerator / denominator

        # 得到裁剪区域
        w_crop = int(crop_mult * w)
        h_crop = int(crop_mult * h)
        x0 = int((w - w_crop) / 2)
        y0 = int((h - h_crop) / 2)

        img_rotated = crop_image(img_rotated, x0, y0, w_crop, h_crop)

    return img_rotated


image_rotated = rotate_image(img, 45, True)
cv2.imshow("test2", image_rotated)

这里写图片描述

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值