Min*_*ber 3 python numpy rotatetransform multidimensional-array
我有一个用numpy创建的3d数组,我想知道如何将其旋转自定义角度,而不仅仅是rot90
numpy 的功能。有人可以帮忙吗?
3d矩阵表示图像(例如立方体或其他形状),即
0:
1 1 1
1 1
1 1 1
1:
1 1
1 1
2:
1 1 1
1 1
1 1 1
Run Code Online (Sandbox Code Playgroud)
编辑:移动解决方案来回答
看一下scipy.ndimage.interpolation.rotate函数。
之所以用科学而不是用麻木,是因为只需改变数组的索引就可以将图像旋转90度。但是,如果要将图像旋转任意角度,则必须处理插值,这将为问题增加新的一层。这是因为当您将旋转图像旋转90度时,原始图像中的所有像素都与旋转图像中的像素“完全对齐”。通常,旋转图像时不是这种情况。
经过一番尝试和错误后,我想出了一些用于我的目的的代码(0 表示数组中为空,另一个数字表示填充的体素。
def rotate(self, deg_angle, axis):
d = len(self.matrix)
h = len(self.matrix[0])
w = len(self.matrix[0][0])
min_new_x = 0
max_new_x = 0
min_new_y = 0
max_new_y = 0
min_new_z = 0
max_new_z = 0
new_coords = []
angle = radians(deg_angle)
for z in range(d):
for y in range(h):
for x in range(w):
new_x = None
new_y = None
new_z = None
if axis == "x":
new_x = int(round(x))
new_y = int(round(y*cos(angle) - z*sin(angle)))
new_z = int(round(y*sin(angle) + z*cos(angle)))
elif axis == "y":
new_x = int(round(z*sin(angle) + x*cos(angle)))
new_y = int(round(y))
new_z = int(round(z*cos(angle) - x*sin(angle)))
elif axis == "z":
new_x = int(round(x*cos(angle) - y*sin(angle)))
new_y = int(round(x*sin(angle) + y*cos(angle)))
new_z = int(round(z))
val = self.matrix.item((z, y, x))
new_coords.append((val, new_x, new_y, new_z))
if new_x < min_new_x: min_new_x = new_x
if new_x > max_new_x: max_new_x = new_x
if new_y < min_new_y: min_new_y = new_y
if new_y > max_new_y: max_new_y = new_y
if new_z < min_new_z: min_new_z = new_z
if new_z > max_new_z: max_new_z = new_z
new_x_offset = abs(min_new_x)
new_y_offset = abs(min_new_y)
new_z_offset = abs(min_new_z)
new_width = abs(min_new_x - max_new_x)
new_height = abs(min_new_y - max_new_y)
new_depth = abs(min_new_z - max_new_z)
rotated = np.empty((new_depth + 1, new_height + 1, new_width + 1))
rotated.fill(0)
for coord in new_coords:
val = coord[0]
x = coord[1]
y = coord[2]
z = coord[3]
if rotated[new_z_offset + z][new_y_offset + y][new_x_offset + x] == 0:
rotated[new_z_offset + z][new_y_offset + y][new_x_offset + x] = val
self.matrix = rotated
Run Code Online (Sandbox Code Playgroud)
我使用上面代码的方式是:
cube = Rect_Prism(20, 20, 20) # creates a 3d array similar to above example, just bigger
cube.rotate(20, "x")
cube.rotate(60, "y")
Run Code Online (Sandbox Code Playgroud)
Rect_Prism 创建一个 MxNxD 矩阵,但在本例中为 NxNxN。
以及打印时的结果:
# # # # # # # # # # # #
# # # # # # #
# # # # # # #
# # # # #
# # # # # # # #
# # # # # # #
# # # # # # # # # # # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # # # #
# # # #
# # # # # # # # # # # #
# # # # #
# # # # # # # #
# # # # # # #
# # # # # # #
# # # # # # #
# # # # # #
# # # # # # # # # # # #
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4244 次 |
最近记录: |