OpenCV实现图像任意角度旋转

不知道是不是因为太简单,OpenCV不屑于去封装还是怎么回事,OpenCV中并没有一个API是专门用于实现图像任意角度的旋转的。我最近由于想要实现一下带旋转的模板匹配,因而必须对图像进行旋转。因此自己写了一个函数。下面是Python版的实现:

import cv2
import matplotlib.pyplot as plt
import numpy as np


def rot_degree(img, degree):
    rows, cols = img.shape
    center = (cols / 2, rows / 2)
    mask = img.copy()
    mask[:, :] = 255
    M = cv2.getRotationMatrix2D(center, degree, 1)
    top_right = np.array((cols - 1, 0)) - np.array(center)
    bottom_right = np.array((cols - 1, rows - 1)) - np.array(center)
    top_right_after_rot = M[0:2, 0:2].dot(top_right)
    bottom_right_after_rot = M[0:2, 0:2].dot(bottom_right)
    new_width = max(int(abs(bottom_right_after_rot[0] * 2) + 0.5), int(abs(top_right_after_rot[0] * 2) + 0.5))
    new_height = max(int(abs(top_right_after_rot[1] * 2) + 0.5), int(abs(bottom_right_after_rot[1] * 2) + 0.5))
    offset_x = (new_width - cols) / 2
    offset_y = (new_height - rows) / 2
    M[0, 2] += offset_x
    M[1, 2] += offset_y
    dst = cv2.warpAffine(img, M, (new_width, new_height))
    mask = cv2.warpAffine(mask, M, (new_width, new_height))
    _, mask = cv2.threshold(mask, 128, 255, cv2.THRESH_BINARY)
    return dst, mask


if __name__ == '__main__':
    img = cv2.imread('messi5.jpg', cv2.IMREAD_GRAYSCALE)
    plt.imshow(img, cmap='gray')
    plt.show()
    dst, mask = rot_degree(img, 30)
    plt.imshow(dst, cmap='gray')
    plt.show()
    plt.imshow(mask, cmap='gray')
    plt.show()

看到代码其实就能了解到,OpenCV其实是可以实现旋转的。最关键的两个OpenCV的函数就是cv2.getRotationMatrix2Dcv2.warpAffine。只是如果要考虑旋转之后画布的大小会发生变化,就还有好多小细节要考虑到。看了代码自然知道,我就不在这里一一说明了。

messi5.png

rotated.png

mask.png
我在streamlit上也实现了一下。可以在此地址体验:

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值