python - 沿 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 没有正确对齐
结果如下:
我应该如何解决它?
解决方案
首先,您正在计算错误的角度。您正在计算的角度介于起源于原点并结束于 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)
推荐阅读
- html - 如何更改django中的默认注册
- python-3.x - 用于命名实体识别的 Spacy 交叉验证
- c# - 为什么 ComputeHash 的执行速度比 certutil -hashfile 慢得多?
- perl - MULTIPLICITY 和 PERL_IMPLICIT_CONTEXT 的关系
- javascript - Wordpress - 如何从优化 JavaScript 代码中排除 google autoaddress js
- pdf - 在 Illustrator 中链接时在 windows 下使用 ggsave 生成 PDF 字体的问题
- microsoft-graph-api - 如何使用 Graph API 获取扩展属性?
- php - 是否可以访问 wordpress 主题上的 php 脚本
- javascript - 理解和转换 Ruby 的 ChunkyPNG 到 Javascript 等价物
- crm - Bitrix24 crm 上的分类自定义字段