繁体   English   中英

如何在Android中使用Opencv裁剪时旋转图像?

[英]How to rotate an image withour cropping it using Opencv in Android?

我在Android中使用Opencv计算检测到的对象的rotation angle ,然后将该对象旋转回其正常位置以进行进一步的图像特征化,例如分割和对象匹配。

这就是我到目前为止

double rect_angle = rbox.angle - 90.0f;
Size rect_size = rbox.size;

double d = rect_size.width;
rect_size.width = rect_size.height;
rect_size.height = d;

M = Imgproc.getRotationMatrix2D(rbox.center, rect_angle, 1.0);
Imgproc.warpAffine(origMat, rotated, M, origMat.size());

如果我稍微旋转一下物体,结果就是

在此处输入图片说明

如果我不旋转对象,这就是我得到的

在此处输入图片说明

我需要保持对象始终居中。

我的问题类似于这个问题,在C ++中的OpenCV中旋转图像而不进行裁剪

但我无法在Java中实现。

我希望你们能帮助我实现这一目标。

PyImageSearch对这个问题有很好的解释。 尽管该解决方案使用Python,但我相信您可以轻松地将数学转换为Java。

目的是使用新输出图像的尺寸来编辑旋转矩阵。 针对旋转效果调整此输出图像的大小。

从PyImageSearch的说明中引用以下代码,您可以看到在修改后的旋转矩阵中考虑了新输出图像的尺寸:

def rotate_bound(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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM