2

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

enter image description here

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

enter image description here

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.

Amine
  • 2,241
  • 2
  • 19
  • 41
  • what exactly is it that stops you from implementing the linked answer in Java? be more specific about your problem. – Piglet Apr 01 '19 at 17:37
  • As you can notice from linked images, when the object(coffret) is rotated some corners aren't visible so my algorithm isn't working. And I implemented the linked answer in java but no luck, the problem is persisting. – Amine Apr 01 '19 at 18:20

1 Answers1

0

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))
Shawn Mathew
  • 2,198
  • 1
  • 14
  • 31