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)

python-OpenCV旋转操作黑边的去除_第1张图片

# 进行旋转操作
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)

python-OpenCV旋转操作黑边的去除_第2张图片

去除黑边操作

# 去除黑边的操作
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)

python-OpenCV旋转操作黑边的去除_第3张图片

你可能感兴趣的:(python)