Reputation: 17
Here is an example of an image. The object in the image seems to be rotated. How do I undo the rotation of it?
Upvotes: 0
Views: 430
Reputation: 515
You can get the contours in the image than convert them to a rotate rect using opencv. the rotate rect will provide you the angle. all you need to do than is to rotate the image using that angle. The code is attached below
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()
the output sample is attached here
Upvotes: 5
Reputation: 528
In the image library from PIL
there is a rotate
method. Here goes an example of function that could help you
from PIL import Image
def rotar(a,t): #a es el nombre de la imagen, t son los grados en deg
colorImage = Image.open(a)
rotated = colorImage.rotate(t, expand=True)
rotated.save('rotated.png')
Upvotes: 0