首页 > 解决方案 > 沿 y 轴逐行旋转(对齐)图像

问题描述

我正在尝试旋转(对齐)图像,其中P1包含P2沿y-axis

原图:

在此处输入图像描述

注:绿色区域代表原图

结果应该是:

在此处输入图像描述

注:红色区域代表旋转后的原图

所以我需要计算由P1(x1,y1)andP2(x2,y2)和 by定义的线之间的角度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)

但是我的rotated_image 没有正确对齐

结果如下:

在此处输入图像描述

我应该如何解决它?

标签: pythonopencv

解决方案


首先,您正在计算错误的角度。您正在计算的角度介于起源于原点并结束于 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)

在此处输入图像描述

在此处输入图像描述


推荐阅读