Issue
I am trying to get a positions of new points P1_r(x1_new, y1_new)
and P2_r(x2_new, y2_new)
after image rotation using imutils.rotate_bound()
. Original image contain line defined by points P1(x1, y2)
and P2(x2, y2)
.
import imutils
import numpy as np
P1 = np.array([x1, y1])
P2 = np.array([x2, y2])
The starting position is as follows (green area represents an image):
Before rotation I have to calculated the angle
between line defined by points P1(x1, y2)
, P2(x2, y2)
and by y-axis
(in this case is y-axis represented by green line):
Then is necessary to calculate the angle
where is used function np.arccos()
:
if (P2[1] - P1[1]) < 0:
y_axis_vector = np.array([0, -1])
else:
y_axis_vector = np.array([0, 1])
if (P2[0] - P1[0]) < 0 and (P2[1] - P1[1]) :
y_axis_vector = np.array([0, 1])
p_unit_vector = (P2 - P1) / np.linalg.norm(P2-P1)
angle = np.arccos(np.dot(p_unit_vector, y_axis_vector)) * 180 / math.pi
Then is possible to rotate the image:
rotated_image = imutils.rotate_bound(original_image, -angle)
So result should looks like:
Now I am trying to calculate positions of new points P1_r(x1_new, y1_new)
and P2_r(x2_new, y2_new)
. I tried to use "standard" sin()
and cos()
functions to calculate new x
and y
positions for point P1_r
:
x1_new = y1 * sin(angle) + x1 * cos(angle)
y1_new = y1 * cos(angle) - x1 * sin(angle)
and for point P2_r
:
x2_new = y2 * sin(angle) + x2 * cos(angle)
y2_new = y2 * cos(angle) - x2 * sin(angle)
However it doesn't work
, because the whole picture is rotated, not only line.
How should I solve this problem?
Solution
Image rotates around its center. Thus for any point, first rotate the point around image center, then adjust for offset in rotated image.
To rotate around given origin:
def rotate(pt, radians, origin):
x, y = pt
offset_x, offset_y = origin
adjusted_x = (x - offset_x)
adjusted_y = (y - offset_y)
cos_rad = math.cos(radians)
sin_rad = math.sin(radians)
qx = offset_x + cos_rad * adjusted_x + sin_rad * adjusted_y
qy = offset_y + -sin_rad * adjusted_x + cos_rad * adjusted_y
return qx, qy
h, w = original_image.shape[:2]
origin = (w/2, h/2)
x1_new, y1_new = rotate([x1, y1], np.radians(angle), origin)
x2_new, y2_new = rotate([x2, y2], np.radians(angle), origin)
Then calculate offset in rotated image:
h_new, w_new = rotated_image.shape[:2]
xoffset, yoffset = (w_new - w)/2, (h_new - h)/2
and adjust points:
x1_new, y1_new = x1_new+xoffset, y1_new+yoffset
x2_new, y2_new = x2_new+xoffset, y2_new+yoffset
Answered By - paiv
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.