围绕特定线旋转 2D numpy 数组

问题描述 投票:0回答:1

我正在尝试围绕图像中绘制的特定线旋转图像。想想随机 2D numpy 数组的图像。我在数组中有两个特定点,我想通过它们绘制一条线。我想以这条线形成新的 x 轴的方式旋转数组/图像。我该怎么做?

一些代码解释:

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

x = np.linspace(-5,5,8)
y = np.linspace(-25,25,7)

z = np.random.randn(7,8)*0.5
z = z/np.max(z)

z[5,6] = 2; z[1,1] = 2

plt.pcolormesh(x,y,z); plt.colorbar()

现在我想在具有最大 z 值的点之间画一条线并旋转数组,使这条线成为新的 x 轴。

我首先尝试获取线条的端点。这些通常是大 z 值的质心,然后通过这些点获得最佳拟合线的斜率。

# get endpoints which lie at the very end of the gaussian distribution
line_endpoints = np.where(z>z.mean()+3*z.std(), 1, 0)
yline, xline = np.nonzero(line_points)
fitline = stats.linregress(x=xline, y=yline)

现在,

fitline
给出了最佳拟合线的斜率和截距。如何使用此斜率旋转原始数组
z
,以便选定的端点形成新的 x 轴?我想看看这样的图像。我查看了 scipy 文档,但找不到任何合适的内容。

python numpy matplotlib image-processing scipy
1个回答
0
投票

scipy.ndimage.rotate()
可以做到这一点。

代码示例:

points_above_3_std = z>z.mean()+3*z.std()
idx = np.array(np.where(points_above_3_std))
endpoint_diff = idx[:, 1] - idx[:, 0]
rot_angle = np.degrees(np.arctan2(endpoint_diff[0], endpoint_diff[1]))
print(rot_angle)
z_rot = scipy.ndimage.rotate(z, rot_angle)
plt.imshow(z_rot[::-1])  # Note: flip y axis to get same direction as pcolormesh plot

剧情:

备注:

  • 我从用斜率描述旋转改为用度数描述旋转。斜坡不能很好地处理 90 度旋转(即,如果应该旋转 90 度,则斜坡将是无限的。)

  • 有两种轮换可以满足您的问题。例如,此处 38 度旋转将两个点置于同一 Y 坐标。然而,旋转 -142 度(这会使图形上下颠倒)也能实现此目的。

    如果你想确保旋转角度在[-90, 90]区间内,可以在

    rotate()
    前添加以下代码。

    rot_angle = (rot_angle + 90) % 180 - 90
    
© www.soinside.com 2019 - 2024. All rights reserved.