Python 3.6:旋转矩阵

2024-10-16 20:41:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有强度数据(扫描电镜.txt)我想通过将行重新指定为列来将图像旋转90度。Python给了我一个“代码分析无效语法”错误,它说“for m:”—我做错什么了?你知道吗

import numpy as np
import matplotlib.pyplot as plt

a=np.loadtxt("SEM.txt")
Intensity=np.loadtxt("SEM.txt")
Intensity[n,m]=Raw_Intensity
for m:
    for n:
        New_Intensity[m,n]=Raw_Intensity[n,m]
plt.imshow(New_Intensity)

Tags: 数据图像importtxtnewforrawas
2条回答

你要做的是变换一个数组。直接使用转置。见numpy transpose

New_Intensity = np.transpose(Intensity)

下面是我建议的演示

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a)
[[1 2 3]
 [4 5 6]]
b = np.transpose(a)
print(b)
[[1 4]
 [2 5]
 [3 6]]

如果你想手动完成,那么你可以这样做。你知道吗

# get the size of the matrix
size = a.shape()
# create the output of the correct size
c = np.zeros((size[1],size[0]))
# iterate over the range of row values
for m in range(size[0]):
# iterate over the range of column values
 for n in range(size[1]):
  c[n,m]=a[m,n]
print(c)
[[ 1.  4.]
 [ 2.  5.]
 [ 3.  6.]]

结果与只使用numpy.transpose相同,但需要更多的输入。你知道吗

for循环语法不正确。你需要这样的东西

for i in some_iterable:
    #do some stuff with i or whatever

不过我很确定你可以用这样的列表来替换那些循环

New_Intensity=[[x[1],x[0]] for x in Raw_Intensity]

假设你真的想这么做。。。。你知道吗

编辑

根据您上面关于需要使用for循环的评论,您可以这样做

New_Intensity=[]
for x in Raw_Intensity:
    #we don't need to define x outside the for loop
    New_Intensity.append([x[1],x[0]])

相关问题 更多 >