我在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());
如果我在这里旋转我的对象,结果就是这里
如果我不旋转这里的对象是我得到的
我需要保持对象始终居中。
我的问题类似于这个问题Rotate an image without cropping in OpenCV in C++
但我无法在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))