简体   繁体   中英

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

I am using Opencv in Android to calculate the rotation angle of a detected object then I rotate that object back to its normal position for further image traitment like segmentation and object matching.

This is what I've got so far

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());

If I rotate my object a little here is the result

在此处输入图片说明

And if I don't rotate the object here is what I get

在此处输入图片说明

I need to keep the object always centered.

My problem is similar to this question Rotate an image without cropping in OpenCV in C++

but I couldn't achieve that in java.

I hope you guys can help me achieve that.

There's an excellent explanation at PyImageSearch for this problem. Although the solution is in Python, I'm sure you can easily translate the math to Java.

The objective is to edit the rotation matrix with the dimensions of a new output image. The size of this output image is adjusted for the effect of the rotation.

Referring the following code from PyImageSearch's explanation, you can see dimensions of the new output image are considered in the modified rotation matrix:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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