1 回答

TA貢獻(xiàn)1765條經(jīng)驗 獲得超5個贊
首先,您正在計算錯誤的角度。您正在計算的角度介于起源于原點并結(jié)束于 P1 的向量與起源于原點并結(jié)束于 P2 的向量之間。
您需要的角度介于從 P1 開始到 P2 結(jié)束[P2-P1]的向量與表示 y 軸方向的向量之間,即[0, 1].
其次,您必須考慮到您的原點位于左上角,因此您需要在計算后反映角度。
import cv2
import numpy as np
from math import *
import math
import imutils
height = 500
width = 500
original_image = np.zeros((height,width,3), np.uint8)
original_image[:] = (0,255,0)
x1 = 400
y1 = 50
P1 = np.array([x1, y1])
x2 = 100
y2 = 300
P2 = np.array([x2, y2])
# checks orientation of p vector & selects appropriate y_axis_vector
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_p_y = np.arccos(np.dot(p_unit_vector, y_axis_vector)) * 180 /math.pi
cv2.line(original_image, tuple(P1), tuple(P2), (0, 0, 0), 3)
print(angle_p_y)
print (P2-P1)
rotated_image = imutils.rotate_bound(original_image, -angle_p_y)
cv2.imshow("Original", original_image)
cv2.imshow("Rotated", rotated_image)
cv2.waitKey(0)
添加回答
舉報