沿 y 轴逐行旋转(对齐)图像

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

原图:

http://img2.mukewang.com/63574a0a00018c6303680356.jpg

注:绿色区域代表原图

结果应该是:

http://img2.mukewang.com/63574a1400015a5d03840362.jpg

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

所以我需要计算由P1(x1,y1)andP2(x2,y2)和 by定义的线之间的角度y-axis

http://img.mukewang.com/63574a1f0001e1d302980274.jpg

我的代码是:


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 没有正确对齐

结果如下:

http://img2.mukewang.com/63574a4100018d5706590659.jpg

我应该如何解决它?



小唯快跑啊
浏览 98回答 1
1回答

POPMUISE

首先,您正在计算错误的角度。您正在计算的角度介于起源于原点并结束于 P1 的向量与起源于原点并结束于 P2 的向量之间。您需要的角度介于从 P1 开始到 P2 结束[P2-P1]的向量与表示 y 轴方向的向量之间,即[0, 1].其次,您必须考虑到您的原点位于左上角,因此您需要在计算后反映角度。import cv2import numpy as npfrom math import *import mathimport imutilsheight = 500width&nbsp; = 500original_image = np.zeros((height,width,3), np.uint8)original_image[:] = (0,255,0)x1 = 400&nbsp;y1 = 50P1 = np.array([x1, y1])x2 = 100y2 = 300P2 = np.array([x2, y2])# checks orientation of p vector & selects appropriate y_axis_vectorif (P2[1] - P1[1]) < 0:&nbsp; &nbsp; y_axis_vector = np.array([0, -1])else:&nbsp; &nbsp; y_axis_vector = np.array([0, 1])if (P2[0] - P1[0]) < 0 and (P2[1] - P1[1]) :&nbsp; &nbsp; y_axis_vector = np.array([0, 1])p_unit_vector = (P2 - P1) / np.linalg.norm(P2-P1)angle_p_y&nbsp; &nbsp; &nbsp;= np.arccos(np.dot(p_unit_vector, y_axis_vector)) * 180 /math.picv2.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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python