我想旋转一个数组,但不是整体,而是其中的一小部分。
我有 512X512 数组(基本上是中心为 (150,150) 半径为 200 的高斯圆)。现在我想将数组的一小部分(中心为 (150,150) 半径为 100)旋转 90 度。最初我使用了 numpy rot90 模块,但它会旋转每个数组元素,这不是我想要的。
要旋转二维数组的一部分,您需要:
以下是实现此目的的分步 Python 代码示例:
import numpy as np from scipy.ndimage import rotate # Create a 512x512 array (example with a Gaussian circle) arr = np.zeros((512, 512)) x, y = np.meshgrid(np.arange(512), np.arange(512)) circle_center = (150, 150) radius = 200 gaussian_circle = np.exp(-((x - circle_center[0]) ** 2 + (y - circle_center[1]) ** 2) / (2 * (radius ** 2))) arr += gaussian_circle # Define parameters for the rotation sub_center = (150, 150) # Center of the subarray to rotate sub_radius = 100 # Radius of the subarray rotation_angle = 90 # Angle of rotation in degrees # Step 1: Extract the subarray x_min = max(sub_center[0] - sub_radius, 0) x_max = min(sub_center[0] + sub_radius, arr.shape[0]) y_min = max(sub_center[1] - sub_radius, 0) y_max = min(sub_center[1] + sub_radius, arr.shape[1]) subarray = arr[x_min:x_max, y_min:y_max] # Step 2: Rotate the subarray rotated_subarray = rotate(subarray, rotation_angle, reshape=False, order=1) # Step 3: Place the rotated subarray back into the original array result = arr.copy() result[x_min:x_max, y_min:y_max] = rotated_subarray # Visualize (Optional) import matplotlib.pyplot as plt plt.figure(figsize=(12, 6)) plt.subplot(1, 2, 1) plt.title("Original Array") plt.imshow(arr, cmap='gray') plt.subplot(1, 2, 2) plt.title("Array After Subarray Rotation") plt.imshow(result, cmap='gray') plt.show()
(150, 150)
radius = 200
radius = 100
scipy.ndimage.rotate
reshape=False
此方法允许您仅旋转数组的特定部分,同时保持其余部分不变。