python读取文件并将内容整成28*28的图像显示
时间: 2023-09-12 21:08:02 浏览: 79
假设你要读取的文件是一个文本文件,其中包含一些数字,可以按照以下步骤将其转换为28x28的图像并显示出来。
1. 读取文件并将其转换为数字列表
```python
with open('filename.txt', 'r') as f:
content = f.read()
# 将字符串转换为数字列表
nums = [int(x) for x in content.split()]
```
在这个示例中,我们使用`with`语句打开文件并读取其内容。然后,我们将字符串转换为数字列表,方法是使用`split()`函数拆分字符串并使用列表推导式将拆分后的字符串转换为整数。
2. 将数字列表转换为28x28的图像
```python
import numpy as np
from PIL import Image
# 将数字列表转换为28x28的数组
arr = np.array(nums).reshape(28, 28)
# 将数组转换为图像
img = Image.fromarray(np.uint8(arr))
# 显示图像
img.show()
```
在这个示例中,我们使用NumPy库将数字列表转换为一个28x28的数组,然后使用PIL库将该数组转换为图像。
3. 完整的代码
```python
import numpy as np
from PIL import Image
with open('filename.txt', 'r') as f:
content = f.read()
# 将字符串转换为数字列表
nums = [int(x) for x in content.split()]
# 将数字列表转换为28x28的数组
arr = np.array(nums).reshape(28, 28)
# 将数组转换为图像
img = Image.fromarray(np.uint8(arr))
# 显示图像
img.show()
```
请注意,此代码假定文件中只包含28x28个数字。如果文件中包含其他内容,请根据需要修改代码。
阅读全文
相关推荐

















