numpy 如何计算图像旋转后新点的位置

qzwqbdag  于 2023-11-18  发布在  其他
关注(0)|答案(2)|浏览(122)

我试图得到一个位置的新点P1_r(x1_new, y1_new)P2_r(x2_new, y2_new)后,图像旋转使用imutils.rotate_bound()。原始图像包含线定义的点P1(x1, y2)P2(x2, y2)

import imutils
import numpy as np

P1 = np.array([x1, y1])
P2 = np.array([x2, y2])

字符串
起始位置如下(* 绿色区域表示图像 *):


的数据
在旋转之前,我必须计算由点P1(x1, y2)P2(x2, y2)y-axis定义的线之间的angle(在这种情况下,* 是由绿色线 * 表示的y轴):



然后有必要计算angle,其中使用函数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


然后可以旋转图像:

rotated_image = imutils.rotate_bound(original_image, -angle)


因此,结果应该如下所示:



现在我尝试计算新点P1_r(x1_new, y1_new)P2_r(x2_new, y2_new)的位置。我尝试使用“标准”sin()cos()函数来计算点P1_r的新位置xy

x1_new = y1 * sin(angle) + x1 * cos(angle) 
y1_new = y1 * cos(angle) - x1 * sin(angle)


P2_r

x2_new = y2 * sin(angle) + x2 * cos(angle)
y2_new = y2 * cos(angle) - x2 * sin(angle)


但是它是doesn't work,因为整个画面都是旋转的,不仅仅是线。
我该如何解决这个问题?

hgqdbh6s

hgqdbh6s1#

图像围绕其中心旋转。因此,对于任何点,首先围绕图像中心旋转该点,然后在旋转图像中调整偏移。
绕给定原点旋转:

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_new, w_new = rotated_image.shape[:2]
xoffset, yoffset = (w_new - w)/2, (h_new - h)/2


调整点数:

x1_new, y1_new = x1_new+xoffset, y1_new+yoffset
x2_new, y2_new = x2_new+xoffset, y2_new+yoffset

u1ehiz5o

u1ehiz5o2#

你可以让opencv为你做计算。

# read image
image = cv2.imread('tony-sebastian-AhMo_n7KRbw-unsplash.jpg')
# Crop for better view
image = image[2000:6000,:,:][::5,::5,:]

# define a point to track @ x=400 and y=700
image[700:720,400:420,:] = 0

# Invert color order to view it with plt.imshow()
image = image[:,:,::-1]

plt.imshow(image)

字符串


的数据

# points to track (x, y)
point_to_track = (400, 700)

# assuming your desired rotation is 60 degrees
angle = -80

# Get the image center (assumes the point of rotation is the image center)
center = (image.shape[1] // 2, image.shape[0] // 2)

# create the rotation matrix which is required to rotate images and points (everything as a numpy array)
rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)

# rotate image
rotated_image = cv2.warpAffine(image, rotation_matrix, image.shape[:2])

plt.imshow(rotated_image)


# find new position of points after rotation
point_after_rotation = cv2.transform(np.array([[point_to_track]]), rotation_matrix)[0][0]

print(point_after_rotation)


[105 452]

相关问题