【发布时间】:2019-12-24 11:27:31
【问题描述】:
我有一个计算图形方向的代码和一个根据计算的方向拉直图形的函数。当我运行代码时,方向似乎很好,但是当函数试图拉直图形时,看起来图形已经变成了另一个形状。会不会是代码有问题?
代码:
import numpy as np
import matplotlib.pyplot as plt
import cv2
img = cv2.imread('path_to_input_image',0)
edges = cv2.Canny(img,1,2,70,3)
img = edges
y, x = np.nonzero(img)
x = x - np.mean(x)
y = y - np.mean(y)
coords = np.vstack([x, y])
cov = np.cov(coords)
evals, evecs = np.linalg.eig(cov)
sort_indices = np.argsort(evals)[::-1]
x_v1, y_v1 = evecs[:, sort_indices[0]]
x_v2, y_v2 = evecs[:, sort_indices[1]]
scale = 30
plt.plot([x_v1*-scale*2, x_v1*scale*2],
[y_v1*-scale*2, y_v1*scale*2], color='red')
plt.plot([x_v2*-scale, x_v2*scale],
[y_v2*-scale, y_v2*scale], color='blue')
plt.plot(x, y, 'k.')
plt.axis('equal')
plt.gca().invert_yaxis()
plt.show()
def rechtzetten(x_v1,y_v1,coords):
theta = np.arctan((x_v1)/(y_v1))
rotation_mat =np.matrix([[np.cos(theta), -np.sin(theta)],[np.sin(theta),np.cos(theta)]])
transformed_mat = rotation_mat*coords
x_transformed, y_transformed = transformed_mat.A
fig = plt.figure()
ax = plt.Axes(fig, [0.,0.,1.,1.])
ax.set_axis_off()
fig.add_axes(ax)
ax = plt.plot(x_transformed,y_transformed)
plt.savefig("ja.png",pdi=300)
plt.show(ax)
#plt.savefig("rotation.png")
img3 = cv2.imread('ja.png',100)
edges2 = cv2.Canny(img3,1,4)
cv2.imwrite('rotated_with_border.png', edges2)
return transformed_mat, edges2
transformed_mat, edges = rechtzetten(x_v1,y_v1,coords)
我使用的输入图片:
我得到的输出:
输出的第一个图使用蓝色和红色轴显示方向。 输出的第二个数字应该是第一个数字的拉直版本。
*我的意思是把第一个图上的蓝色和红色轴与基本坐标系上的 x 和 y 轴匹配。
【问题讨论】:
-
我无法回答您的问题。也许旋转矩阵是转置的。但是为什么你不只是得到旋转的边界矩形(docs.opencv.org/2.4/modules/imgproc/doc/…)。然后是它的4个角。然后得到RotationMatrix2D。然后是warpAffine。参见例如 gist.github.com/Ankita-Das/82bce39b35d1bbeca2ce87c4e8aba33d 和 jdhao.github.io/2019/02/23/crop_rotated_rectangle_opencv
-
我不知道你的转换会发生什么,但你应该使用 opencv getRotationMatrix2D 命令和你估计的“theta”,然后将此命令的输出提供给 opencv warpAffine 命令。
-
感谢您的建议,我会研究一下。
标签: python numpy opencv image-manipulation