【发布时间】:2020-02-25 08:08:27
【问题描述】:
我正在尝试将所有图像对齐为垂直/水平。我必须使用以下代码旋转图像:
import cv2
import imutils
import numpy as np
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))
image = cv2.imread("10247.png")
# loop over the rotation angles again, this time ensuring
# no part of the image is cut off
dim=(600,400)
im=rotate_bound(image,30)
im = cv2.resize(im, dim, interpolation = cv2.INTER_AREA)
cv2.imshow("Rotated (Correct)", im)
cv2.waitKey(0)
cv2.destroyWindow("Rotated (Correct)")
for angle in np.arange(0, 360, 15):
rotated = imutils.rotate_bound(image, angle)
dim=(800,600)
resized = cv2.resize(rotated, dim, interpolation = cv2.INTER_AREA)
cv2.imshow("Rotated (Correct)", resized)
cv2.waitKey(0)
cv2.destroyWindow("Rotated (Correct)")
我希望在图像垂直/水平时停止旋转。我该如何阻止它?如何确定当前角度?
【问题讨论】:
-
你将不得不引入一些自上而下的知识并在图像中检测它。例如。您可以在图像边界区域中搜索“大亮臂部分”并旋转图像直到它位于图像底部的中心。或者您可以尝试检测手指(例如使用凸面缺陷函数)并旋转直到它们位于顶部,居中。
-
@nathancy 我尝试了你提到的所有方法来检查角度,但我得到了错误的结果。我需要将图像旋转 30 度左右,但我使用上述方法得到了 260 度左右。
标签: python image opencv rotation orientation