我试图旋转(对齐)图像,该图像包含沿P1
的线(具有两个点P2
和y-axis
)
注意:绿色区域代表原始图像
注意:红色区域代表旋转后的原始图像
所以我需要计算P1(x1,y1)
和P2(x2,y2)
以及y-axis
定义的线之间的角度,
注意:绿线代表y轴
我的代码是:
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 = (x1, y1)
x2 = 100
y2 = 300
P2 = (x2, y2)
cv2.line(original_image, P1, P2, (0, 0, 0), 3)
deltaY = y1 - y2
deltaX = x1 - x2
angleInDegrees = atan2(deltaY, deltaX) * 180 / math.pi
print(angleInDegrees)
rotated_image = imutils.rotate_bound(original_image, angleInDegrees)
cv2.imshow("Original", original_image)
cv2.imshow("Rotated", rotated_image)
cv2.waitKey(0)
但是我的旋转图像未正确对齐
结果如下:
我应该如何解决?
答案 0 :(得分:2)
首先,您要计算错误的角度。您要计算的角度介于起点和终点P1之间的向量与起点和终点P2之间的向量之间。
您需要的角度介于从P1开始到P2结束[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)