图像旋转90度整数倍

通常图像的旋转使用

cv2.getRotationMarix2D(获取变换矩阵)
cv2.warpAffine(进行仿射变换)

这两个API较多,但是变换过后往往会截断部分图像的内容

另外看到一种思路是创建一个全0数组去放置变换后的图片, 然后截去非图片部分, 如果是旋转90度这种特殊角度, 可以手动构建旋转矩阵matRotate ,以保证仿射 平移后的图片不会有缺失, 但经过测试, 这种方式还是存在风险, 因此仅提供一种思路, 代码如下:

def rotate(image, angle):
     """
     :param image: 原图像
     :param angle: 旋转角度
     :return: 旋转后的图像
     """
     height, width = image.shape[:2]
     matRotate = cv.getRotationMatrix2D((height // 2, width // 2), angle, 1)
     dst = cv.warpAffine(image, matRotate, (width * 2, height * 2))
     rows, cols = dst.shape[:2]
     for col in range(0, cols):
         if dst[:, col].any():
             left = col
             break
     for col in range(cols - 1, 0, -1):
         if dst[:, col].any():
             right = col
             break
     for row in range(0, rows):
         if dst[row, :].any():
             up = row
             break
     for row in range(rows - 1, 0, -1):
         if dst[row, :].any():
             down = row
             break
     res_widths = abs(right - left)
     res_heights = abs(down - up)
     res = np.zeros([res_heights, res_widths, 3], np.uint8)
     for res_width in range(res_widths):
         for res_height in range(res_heights):
             res[res_height, res_width] = dst[up + res_height, left + res_width]
     return res

最后是这样解决的: 仅旋转90 180 270三个角度的话, 通过转秩和翻折的方式就能够达到效果

def rotate(image, angle):
    """
    :param image: 原图像
    :param angle: 旋转角度
    :return: 旋转后的图像
    """
    if angle == 0:
        return image
    if angle == 90:
        dst1 = cv.transpose(image)
        dst2 = cv.flip(dst1, 0)
        return dst2
    if angle == 180:
        dst1 = cv.flip(image, 1)
        dst2 = cv.flip(dst1, 0)
        return dst2
    if angle == 270:
        dst1 = cv.transpose(image)
        dst2 = cv.flip(dst1, 1)
        return dst2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值