Krupali Mistry
Krupali Mistry

Reputation: 644

rotate an image based on the two coordinates

I have many images which contains two points, one at the top and another at the bottom. As well as I have the coordinates stored in the excel file too. I want to roatate the image so that it is 90 degrees.Below is the image which contains two coordinates. enter image description here

The red color signifies the actual image using the coordinates and the angle is 85 degrees (approx), so iwant to rotate the image and make it 90 degrees as shown with yellow in the figure.

Can someone help me with this which api or functions to use. (I am using Python for coding) enter image description here

Upvotes: 1

Views: 1183

Answers (1)

furas
furas

Reputation: 142651

It is basic math with angles in triangle.

if you have two points (x1,y1), (x2, y2) then you can calculate dx = x2-x1, dy = y2-y1 and then you can calculate tangens_alpha = dy/dx and alpha = arcus_tangens(tangens_alpha) and you have angle which you hava to use to calculate rotation - 90-alpha

enter image description here


In Python it will be as below. I took points from your image.

Because image have (0,0) in top left corner, not in bottom left corner like in math so I use dy = -(y2 - y1) to flip it

import math

x1 = 295
y1 = 605

x2 = 330
y2 = 100

dx = x2 - x1
dy = -(y2 - y1)

alpha = math.degrees(math.atan2(dy, dx))
rotation = 90-alpha

print(alpha, rotation)

And now you can use PIL/pillow or cv2+imutils to rotate it

import math
import cv2
import imutils

x1 = 295
y1 = 605

x2 = 330
y2 = 100

dx = x2 - x1
dy = -(y2 - y1)

alpha = math.degrees(math.atan2(dy, dx))
rotation = 90-alpha
print(alpha, rotation)

img = cv2.imread('image.jpg')

img_2 = imutils.rotate(img, rotation) 
cv2.imwrite('rotate.jpg', img_2)

img_3 = imutils.rotate_bound(img, -rotation)
cv2.imwrite('rotate_bound.jpg', img_3)

cv2.imshow('rotate', img_2)
cv2.imshow('rotate_bound', img_3)

cv2.waitKey(0)

rotate.jpg

enter image description here

rotate_bound.jpg

enter image description here

Upvotes: 3

Related Questions