如何撤消图像的旋转?
这是一个图像示例。图像中的对象似乎已旋转。我如何撤消它的旋转?
回答
您可以获得图像中的轮廓,而不是使用 opencv 将它们转换为旋转矩形。旋转矩形将为您提供角度。您需要做的就是使用该角度旋转图像。代码附在下面
import cv2
import numpy as np
img = cv2.imread("opencv_task.png",0)
con , _ = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
minRect = cv2.minAreaRect(con[0])
## uncomment these if you want to draw a rectangle
# box = cv2.boxPoints(minRect)
# box = np.intp(box) #np.intp: Integer used for indexing (same as C ssize_t; normally either int32 or int64)
# cv2.drawContours(img, [box], 0, (255,255,0))
(h, w) = img.shape[:2]
(cX, cY) = (w // 2, h // 2)
#minRect[2] is the angle of the rotate rectangle
# rotate our image by minRect[2] degrees around the center of the image
M = cv2.getRotationMatrix2D((cX, cY), minRect[2], 1.0)
rotated = cv2.warpAffine(img, M, (w, h))
cv2.imshow("Rotated", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
输出示例附在此处