将图像旋转90度、180度或270度。

30

我需要将一张图片旋转90度、180度或270度。在OpenCV4Android中,我可以使用:

Imgproc.getRotationMatrix2D(new Point(center, center), degrees, 1);
Imgproc.warpAffine(src, dst, rotationMatrix, dst.size());

然而,这是我图像处理算法的一个巨大瓶颈。当然,将图像旋转多个90度的简单旋转比warpAffine的最普通情况要简单得多,并且可以更有效地完成。例如,对于180度,我可以使用:

Core.flip(src, dst, -1);

当值为-1时,表示对水平和垂直轴进行翻转。是否有类似的优化方法可用于90度或270度旋转?


你已经完成了Java的解决方案吗?能否发布一下呢? - Abhishek Choudhary
Core.rotate(mRgba, mRgba, Core.ROTATE_180);Core.flip(mRgba, mRgba, -1);在我的小米红米4 Prime上都需要大约12-14毫秒的CPU时间。性能非常差。我想反转相机字节帧,但这太耗费资源了。 - user924
11个回答

0

这是一个旋转任意角度的函数 [-360 ... 360]
def rotate_image(image, angle):
    # Grab the dimensions of the image and then determine the center
    (h, w) = image.shape[:2]
    (cX, cY) = (w / 2, h / 2)

    # Grab the rotation matrix (applying the negative of the
    # angle to rotate clockwise), then grab the sine and cosine
    # (i.e., the rotation components of the matrix)
    M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])

    # Compute the new bounding dimensions of the image
    nW = int((h * sin) + (w * cos))
    nH = int((h * cos) + (w * sin))

    # Adjust the rotation matrix to take into account translation
    M[0, 2] += (nW / 2) - cX
    M[1, 2] += (nH / 2) - cY

    # Perform the actual rotation and return the image
    return cv2.warpAffine(image, M, (nW, nH))

使用方法

import cv2
import numpy as np

image = cv2.imread('1.png')
rotate = rotate_image(image, angle=90)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接