打印numpy数组的全部内容

2024-09-25 18:21:56 发布

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

我在python中处理图像处理,我想输出一个变量,现在变量b是一个具有形状(200,200)的numpy数组。当我做print b时,我看到的是:

array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       ..., 
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.]])

如何打印出这个数组的全部内容,将其写入一个文件或一些简单的东西,以便我可以查看完整的内容?


Tags: 文件numpy内容数组array图像处理形状print
2条回答

当然,可以使用以下命令将数组的打印阈值更改为answered elsewhere

np.set_printoptions(threshold=np.nan)

但根据你想看的东西,也许有更好的方法。例如,如果您的数组如您所示大部分为零,并且您想检查它是否有非零的值,您可以查看如下内容:

import numpy as np
import matplotlib.pyplot as plt

In [1]: a = np.zeros((100,100))

In [2]: a
Out[2]: 
array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       ..., 
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.]])

更改某些值:

In [3]: a[4:19,5:20] = 1

看起来还是一样的:

In [4]: a
Out[4]: 
array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       ..., 
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.]])

检查一些不需要手动查看所有值的内容:

In [5]: a.sum()
Out[5]: 225.0

In [6]: a.mean()
Out[6]: 0.022499999999999999

或者策划:

In [7]: plt.imshow(a)
Out[7]: <matplotlib.image.AxesImage at 0x1043d4b50>

或保存到文件:

In [11]: np.savetxt('file.txt', a)

array

to_print = "\n".join([", ".join(row) for row in b])
print (to_print) #console

f = open("path-to-file", "w")
f.write(to_print) #to file

如果是numpy数组:Print the full numpy array

相关问题 更多 >