簡體   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