1

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

4
  • 1
    if you have two points then you can calculate distance dx and dy and you can use it to calculate (as I remeber) tan(alpha) = dy/dx and then you can calculate alpha = atan(dy/dx). You can calculate alpha with standard module math. And when you have alpha then you can use PIL/pillow or cv2 to rotate it. Commented Feb 12, 2020 at 2:49
  • @furas Can you explain me using a example? Commented Feb 12, 2020 at 3:06
  • just curious @KrupaliMistry whats this image ? Commented Feb 12, 2020 at 12:51
  • @Ajinkya Its a crab image Commented Feb 13, 2020 at 1:13

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.